Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: PHP Material
Description: here are available for php martial , it is useful to in you're exam

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


PHP MATRIAL BY

KARTIK JOSHI

TOPIC-1
CSS
Marks-10
1) Introduction of Style sheet:








CSS Means:
Full form of CSS is Cascading Style Sheets
Styles define how to display HTML elements
Styles are normally stored in Style Sheets
Styles were added to HTML 4
...
They were supposed to say "This is a header", "This is a
paragraph", "This is a table", by using tags like

,

,

, and
so on
...

 As the two major browsers - Netscape and Internet Explorer - continued
to add new HTML tags and attributes (like the tag and the color
attribute) to the original HTML specification, it became more and more

difficult to create Web sites where the content of HTML documents was
clearly separated from the document's presentation layout
...
0
...

 CSS Can Save a Lot of Work:

Styles sheets define HOW HTML elements are to be displayed,
just like the font tag and the color attribute it HTML 3
...
Styles
are normally saved in external
...
External style sheets
enable you to change the appearance and layout of all the pages in
your Web, just by editing one single CSS document!

CSS is a breakthrough in Web design because it allows
developers to control the style and layout of multiple Web pages
all at once
...

To make a global change, simply change the style, and all
elements in the Web are updated automatically
...
Styles
can be specified inside a single HTML element, inside the
element of an HTML page, or in an external CSS file
...

 What style will be used when there is more than one style specified
for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a
new "virtual" style sheet by the following rules, where number four has
the highest priority:
1
...
External style sheet
3
...
Inline style (inside an HTML element)
 Syntax is:

tags
...
tags
...

 The CSS syntax is made up of 3 parts: a selector, a property and a value
...
The property and value are separated by a colon and surrounded
by curly braces:
body {color: black}
 If the value is multiple words, put quotes around the value:
p {font-family: "sans serif”}
 If you wish to specify more than one property, you must separate each
property with a semi-colon
...
Separate each selector with a comma
...
All header
elements will be green:
H1,H2,H3,H4,H5,H6
{
color: green
}

2) Types of Style sheet:-

 Method to Insert Style Sheet:
 When a browser reads a style sheet, it will format the document
according to it
...

- With an external style sheet, you can change the look of an entire Web
site by changing one file
...

- The tag goes inside the head section:


This is a paragraph with center align
...


o You can also omit the tag name in the selector to define a style that will
be used by all HTML elements that have a certain class
...
center {text-align: center}
In the code below both the h1 element and the p element have
class="center"
...
center" selector:


This heading will be center-aligned


This paragraph will also be center-aligned
...

o The style rule below will match any element that has an id attribute with
a value of "green":
#green {color: green}
The rule above will match both the h1 and the p element:

Some text data


p#para 1
{
text-align: center;

color: red
}
o The style rule below will match any p element that has an id attribute
with a value of "green":
p#green {color: green}
o The rule above will not match an hl element:

Some text data


 Comments in CSS:
You can insert comments into CSS to explain your code, which can help
you when you edit the source code at a later date
...
A CSS comment begins with “/*”, and end with “*/”,
like this:
/* This is a comment */
p
{
text-align: right;
/* This is comment
...





o
o
o

Font-family property
Font-style property
Font-weight property
Font-size property

 Font-family property:
The font-property is a prioritized list of font family names and/or generic
family names for an element
...

Separate each value with a comma
...


Example:
body
{ font-family: courier, serif}
p
{ font-family: arial, “lucida console”, sans-serif}


 Font-style property:
o The font-style property sets the style of a font
...

Value
Normal
Bold
Bolder
Lighter
100 to 900

Description
Defines normal characters
Defines thick characters
Defines thicker characters
Defines lighter characters
Defines from thin to thick characters
...


Example:
P
{font-weight: bold}
o

 Font-size property:
The font-size property sets the size of a font
...


It sets the font-size to smaller size than the
parent element
...

It sets the font-size to a fixed size
...


Example:
Body
{font-size: x-large}
P
{font-size: 10px}
o

 Font-variant property:
The font-variant property is used to display text in a small-caps font,
which means that all the lower case letters are converted to uppercase
letters, but all the letters in the small-caps font have a smaller font-size
compared to the rest of the text
...

It displays small-caps font
...


 It is possible to change the color of a text, increase or decrease the space
between characters in a text, align a text, decorate a text, indent the first
line in a text, and more
...

Value
Color

Description
The color value can be a color name(red), a rgb
value (rgb(255,0,0)), or a hex number(#ff0000)
...

Value
Left
Right
Center
Justify

Description
It aligns the text to the left
...

It Centers the text
...


Examples:
p
{ text-align: center }
 Text-decoration property
- The text-decoration property decorates the text
...

Value

Description
Defines normal text, with lower case letters and
capital letters
Each word in a text starts with a capital letter
Defines only capital letters
Defines no capital letters, only lower case letters

None
Capitalize
Uppercase
Lowercase

Example:
P
{ text-transform: uppercase

}

 Word-spacing property
- The word-spacing property increases or decreases the white space
between words
...

Value
Normal
Length

Description
Defines normal space between words
...


Example:
P
{ word-spacing:30px }
p
{ word-spacing: -0
...


-

Negative values are allowed
...


Length

Defines a fixed space between characters
...
10px

}

6) CSS Background Property: CSS Background Properties:
 The CSS background properties allow you to control the background
color of an element, set an image as the background, repeat a
background image vertically or horizontally, and position an image on a
page
...

Value
Color

Transparent
Example:
p
{

-

Description
The color value can be a color name (red), a
rgb value (rgb(255,0,0)), or a hex number
(#ff0000)
The background color is transparent

background-color: #00ff00 }

Background-image property
The background-image property sets an image as the
background
...


Value

Description

url
None

The path to an image
No background image
Example:
Body
{
background-image: url(stars
...


Value

Description
The background image will be repeated vertically
and horizontally
The background image will be repeated
horizontally
The background image will be repeated vertically
The background image will be displayed only
once

Repeat
Repeat-x
Repeat-y
No-repeat

Example:
body
{
background-image: url(stars
...

Value
Scroll
Fixed

Description
The background image moves when the rest of the
page scrolls
The background image does not move when the rest
of the page scrolls
...
gif);
background-attachment: scroll
}

-

Background-position property
The background-position property sets the starting position of a
background image
...


The first value is the horizontal position and the second
value is the vertical
...
The
right bottom corner is 100% 100%
...

The first value is the horizontal position and the second
value is the vertical
...
Units can be
pixels(0px 0px) or any other CSS units
...
You can mix %
and positions
...
gif);
background-repeat: no-repeat;
background-position: top left
}

7) CSS Border Property: CSS Border Properties:
 The CSS border properties allow you to specify the style and color of an
element's border
...

 Border-style property
- The border-style property sets the style of the 4 borders, can have from 1
to 4 styles
...
Renders as solid in most browsers
Defines a dashed border
...
The width of the two borders are the
same as the border-width value
Defines a 3D grooved border
...
The effect depends on the
border-color value
Defines a 3D inset border
...
The effect depends on the
border-color value
Example:
Table { border-style: dotted dashed solid double }

 The top border will be dotted, right border will be dashed, bottom
border will be solid, left border will be double
...
This property can
one to four colors
...
An element must have borders before you change the color of
them
...

The border is transparent
...

Value
Thin
Medium
Thick
Length

Description
Defines a thin border
...

Defines a thick border
...


Example:
table {border-width: thin}
 All four borders will be thin
table {border-width: thin medium thick none}
 Top border will be thin, right border will be medium, bottom
border will be thick- left side will have no border
 Border-top-width property
- The border-top-width property sets the width of an element's top border
...

Defines a medium top border
...

Allow you to define the thickness of the top
borders
...
5cm
}
 Border-bottom-width
- The border-bottom-width sets the width of an element’s bottom border
...

Example:
table
{
border-bottom-width: thin
}
 Border-left-width property
- The border-left- width property sets the width of an element's left border
...

Example:
table
{
border-left-width: thin
}
 Border-right-width property
- The border-right-width property sets the width of an element's right
border
...

Value
Border-top-width
Border-style
Border-color

Description
Sets the properties for the top border
...

Value : Same to border-top property
...

- This property can not set a different value for each side of the border,
like "margin" and "padding"
...


border-style
border-color
Example:
P
{
border: thin dotted #00FF00
}

8) CSS List Property: CSS List Properties:
 The CSS list properties allow you to place the list-item marker, change
between different list-item markers, or set an image as the list-item
marker
...

- Some browsers only support the “disc” value
...
)
The marker is lower-roman (i, ii, iii, iv, v, etc
...
)
The marker is lower-alpha (a, b, c, d, e, etc
...
)
The marker is lower-greek (alpha, beta, gamma, etc
...

Value
Inside
Outside

Description
Indents the marker and the text
...

- Always specify a "list-style-type" property in case the image is
unavailable
...
gif);
list-style-type: circle
}
o List-style property
- The list-style property is a shorthand property for setting all the
properties for a list in one declaration
...
Negative values are not allowed
...
A shorthand padding property is also created to control
multiple sides at once
...

- Negative values are not allowed
...

- Negative values are not allowed
...

- Negative values are not allowed
...
The values comes in % (defines
padding in % of the width of the closest element) and
length (defines a fixed padding)
...
It is
possible to use negative values to overlap content
...
A shorthand margin property can also be used to change all of
the margins at once
...
Opera does
not! Instead, Opera applies a default padding of 8px, so if one wants to
adjust the margin for an entire page and have it display correctly in
Opera, the body padding must be set as well!
^ margin-top Property
^ margin-bottom Property
^ margin-left Property
^ margin-right Property
^ margin Property
o Margin-top property
- The margin-top property sets the top margin of an element
...

Value

Description

Auto
Length
%

The browser sets a top margin
Defines a fixed top margin
Defines a top margin in % of the total height of the
document
Example:
Hl
{
h2
{

margin-top: 10px
margin-top: -20px

}
}

o Margin-bottom property, margin-left property, margin-right
property
- The margin-bottom property, margin-left property & margin-right
property sets the bottom margin, left margin & right margin of an
element respectively
...

Value : Same to margin-top property
Example:
hl
{
h2
{

margin-left: 10px ; margin-right: 10px
margin-bottom: -20px

}

}

o Margin property
- The margin property is a shorthand property for setting all of the
properties for the four margins in one declaration
...

Value
margin-top
margin-right
margin-bottom
margin-left

Description
Sets the properties for the margins
...


Example:
h1 { margin: 10px
}
 all four margins will be 10px
hl {
margin: 10px 2%
}
 top and bottom margin will be 10px, left and right margin will be
2% of the total width of the document
...

h1 {
margin: 10px 2% -10px auto}
 top margin will be 10px, right margin will be 2% of the total
width of the document, bottom margin will be -10px, left margin
will be set by the browser
...


Marks-20

Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design,
validate forms, detect browsers, create cookies, and much more
...

What is JavaScript?







JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
Everyone can use JavaScript without purchasing a license
Are Java and JavaScript the Same?

NO!
Java and JavaScript are two completely different languages in both
concept and design!
Java (developed by Sun Microsystems) is a powerful and much more
complex programming language - in the same category as C and C++
...
write("

" + name + "

") can write
a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute
when something happens, like when a page has finished loading or when
a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can
read and change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server
...

Eg
...
write("Hello World!");




HTML Comments to Handle Simple Browsers

Browsers that do not support JavaScript will display JavaScript as page
content
...

Just add an HTML comment tag (end of comment) after the last JavaScript statement
...
write("Hello World!");
//-->




The two forward slashes at the end of comment line (//) is the JavaScript
comment symbol
...

Where to put the javascript?

JavaScripts in the body section will be executed WHILE the page loads
...

JavaScripts in a page will be executed immediately while the page loads
into the browser
...
Sometimes we want
to execute a script when a page loads, other times when a user triggers an
event
...
When you place a
script in the head section, you will ensure that the script is loaded before
anyone uses it
...




Scripts in the body section: Scripts to be executed when the page loads
go in the body section
...








Using an External JavaScript

Sometimes you might want to run the same JavaScript on several pages,
without having to write the same script on every page
...
Save the
external JavaScript file with a
...

Note: The external script cannot contain the





Note: Remember to place the script exactly where you normally would
write the script!

JavaScript Comments

Comments can be added to explain the JavaScript, or to make it more
readable
...

JavaScript Multi-Line Comments

Multi line comments start with /* and end with */
...

A variable can have a short name, like x, or a more descriptive name,
like carname
...

You can declare JavaScript variables with the var statement
...


Operator

The operator = is used to assign values
...

The assignment operator = is used to assign values to JavaScript
variables
...

y=5;
z=2;
x=y+z;

The value of x, after the execution of the statements above is 7
...

Given that y=5, the table below explains the arithmetic operators:
Operator
+
*
/
%
++
--

Description
Addition
Subtraction
Multiplication
Division
Modulus (division
remainder)
Increment
Decrement

Example
x=y+2
x=y-2
x=y*2
x=y/2
x=y%2

Result
x=7
x=3
x=10
x=2
...


Given that x=10 and y=5, the table below explains the assignment
operators:
Operator
=
+=
-=
*=
/=
%=

Example
x=y
x+=y
x-=y
x*=y
x/=y
x%=y

Same As
x=x+y
x=x-y
x=x*y
x=x/y
x=x%y

Result
x=5
x=15
x=5
x=50
x=2
x=0

The + Operator Used on Strings:

The + operator can also be used to add string variables or text values
together
...

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains
"What a very nice day"
...
write(x);
x="5"+"5";
document
...
write(x);
x="5"+5;
document
...

Comparison and Logical Operators:

Comparison and Logical operators are used to test for true or false
...

Given that x=5, the table below explains the comparison operators:
Operator
==
===
!=
>
<
>=
<=

Description
is equal to
is exactly equal to (value
and type)
is not equal
is greater than
is less than
is greater than or equal to
is less than or equal to

Example
x==8 is false
x===5 is true
x==="5" is false
x!=8 is true
x>8 is false
x<8 is true
x>=8 is false
x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare
values and take action depending on the result:
if (age<18) document
...

Logical Operators

Logical operators are used to determine the logic between variables or
values
...

Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable
greeting will be assigned the value "Dear President " else it will be
assigned "Dear"
...


Conditional & Looping Structure

Conditional Statements
Conditional statements in JavaScript are used to perform different
actions based on different conditions
...
You can use conditional statements in your code
to do this
...
else statement - use this statement if you want to execute some
code if the condition is true and another code if the condition is false
if
...
else statement - use this statement if you want to select
one of many blocks of code to be executed
switch statement - use this statement if you want to select one of many
blocks of code to be executed

* If Statement

You should use the if statement if you want to execute some code only if
a specified condition is true
...
Using uppercase letters (IF)
will generate a JavaScript error!
* If
...
else statement
...
else if
...
else if
...

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

* Switch Statement

You should use the switch statement if you want to select one of many
blocks of code to be executed
...
The value of the expression is then
compared with the values for each case in the structure
...
Use
break to prevent the code from running into the next case automatically
...
This
repetition can be for a predefined number of times or it can go until
certain conditions are met
...

For this purpose, Javascript offers 2 types of loop structures:
1) for Loops - This loop iterate a specific number of times as specified
...

For Loop
The for loop is the most basic type of loop and resembles a for loop in
most other programming languages, including ANSI ‘C’
...
The declaration of the counter variable can also be done here
itself, condition specifies the final value for the loop to fire (i
...
the loop
fires till condition evaluates to true), expression2 specifies how the initial
value in expression1 is incremented
...
write(n);
}
While Loop
The while loop provides a similar functionality
...
The javascript commands execute as long as the
condition is true
...
write(n);
n++;
}

 4
...

1…
...

When an alert box pops up, the user will have to click "OK" to proceed
...
Confirm Box

A confirm box is often used if you want the user to verify or accept
something
...

If the user clicks "OK", the box returns true
...

Syntax:

confirm("sometext");

3…
...

When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value
...
If the user clicks
"Cancel" the box returns null
...


Array

The Array object is used to store multiple values in a single variable
...

For
...
in statement to loop through the elements of an array
...

Put array elements into a string - join()
-How to use the join() method to put all the elements of an array into a
string
...


Numeric array - sort()
-How to use the sort() method to sort a numeric array
...

1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:
Var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then
the type of variables will be numeric or Boolean instead of string
...
The index number starts at 0
...
write(myCars[0]);

will result in the following output:
Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array
with a specified index number:

myCars[0]="Opel";

Now, the following code line:
document
...

Syntax for creating an Array object:
var myCars=new Array("Saab","Volvo","BMW")

To access and to set values inside an array, you must use the index
numbers as follows:




myCars[0] is the first element
myCars[1] is the second element
myCars[2] is the third element

Array Object Properties
Property
constructor
Index
Input
Length
prototype

 6
...

A user defined function first needs to be declared and coded
...

Functions can accept information in the form of arguments and can
return results
...


Declaring Function:
Functions are declared and created using the function keyword
...

2) A list of parameters (arguments) that will accept values passed to the
function when called
...

Syntax:
function function_name(parameter1,parameter2,
...
The list of parameters passed to the function
appears in parentheses and commas separate members of the list
...
Preferably,
functions are created within the … tags of the HTML
file
...
If the function is called before it is declared and
parsed, it will lead to an error condition, as the function has not been
evaluated and the ‘Browers’ does not know that it exists
...










Passing Parameters:
Values can be passed to function parameters when a ‘parameterized’
function is called
...
Multiple values can be
passed, separated by commas provided that the function has been coded
to accept multiple parameters
...
During declaration, a
function needs to be informed about the number of values that will be
passed
...

So, functions that are going to return a value must use the return
statement
...


 7
...
Use getFullYear()
instead !!
Sets the day of the month in a Date object (from 1-31)

setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setYear()

Sets the year in a Date object (four digits)
Sets the hour in a Date object (from 0-23)
Sets the milliseconds in a Date object (from 0-999)
Set the minutes in a Date object (from 0-59)
Sets the month in a Date object (from 0-11)
Sets the seconds in a Date object (from 0-59)
Sets the year in the Date object (two or four digits)
...


Description
Joins two or more arrays and returns the result
Puts all the elements of an array into a string
...

Using objects can help make programming easier and more streamlined
...

The process uses functions in a slightly modified way
...

Making a new object entails two steps:



Define the object in a user-defined function
...


Here's an example of the world's simplest user-defined JavaScript object:
// this part creates a new object
ret = new makeSimpleObject();
// this part defines the object
function makeSimpleObject() {}

I've called the new object ret; use any valid variable name for the new
object (I use lower-case letters for variables that contain objects, so it's
easier to tell that the variable contains an object)
...
For instance, these lines create four new and separate objects:
eenie, meenie, minie, and moe:
eenie = new makeSimpleObject();
meenie = new makeSimpleObject();
minie = new makeSimpleObject();
moe = new makeSimpleObject();

Actually, there is even a shortcut to the above "world's simplest
JavaScript object
...
JavaScript supports a generic Object() object, which
you can use to make new objects
...
But instead
of just assigning a value to the object itself, you should define a new
property for the object, and assign a value to the property
...
property = value;




myobject is the name of the user-defined object
...

value is the value you want to assign
...
Here's one way to do it:
customer = new makeSimpleObject();
customer
...
address = "123 Main Street";
customer
...
For example, you could put this after the customer
...
When you run the script the alert box will say "Fred
...
name);

Defining properties when you create the object
Another method of defining properties for objects is to include the
property names in the object function
...
All it
takes is a few more lines of code in the object function
...
name);
function makeCustomer(Name, Address, Phone) {
this
...
address = Address;
this
...
Each this statement assigns a
property to the current object, which is the one being created in the
makeCustomer object function
...

These parameters are used to define the contents of the three properties,
which are name, address, and phone
...
To include as customer object, just do this:
customer = new makeCustomer("Fred", "123 Main Street",
"555-1212");
customer
...
";

Note that other objects you create with the makeCustomer object function
will have just the three base properties, but this object for Fred will have an
additional property for the salutation
...

 9
...

Document Object Properties











alinkColor - The color of active links
...
It is set in the tag
...

document
...

defaultCharset
domain - The domain name of the document server
...

fgColor - The text color attribute set in the tag
...

 layers - An array containing all the layers in a document
...
It is specified
in the tag
...

 security
 title - The name of the current document as described between the
header TITLE tags
...

 vlinkColor - The color of visited links as specified in the tag/
Document Object Methods




clear() - This is depreciated
...

contextual() - It can be used to specify stype of specific tags
...
contextual(document
...
blockquote)
...

document
...
tags
...
tags
...
color =
"blue";






elementFromPoint(x, y) - Returns the object at point x, y in the HTML
document
...

open([mimeType]) - Opens a new document object with the optional MIME
type
...
exprN]) - Add data to a document
...

document
...
writeln("This is a Header")
document
...
exprN]) - Adds the passed values to the document
appended with a new line character
...

anchors - An array of all the anchors in the document
...

area - An object specifying an image map area contained in the
document
...

forms - An array of all the forms in the document
...

images - An array of the images in the document
...
Properties of the image:
border - The width of the border around the image in pixels
...

height - The read only height of the image in pixels
...

lowsrc - The read or write string giving the URL of an alternate image
for low resolution screen display
...

prototype - Used for adding user-specified properties to the image
...
It is a read/write string
...

width - The read only width of the image in pixels
...

link - A link in the document
...

host - The URL hostname and port
...

href - The URL
...

port - The URL port section
...

search - The URL query string section
...

target - The URL link’s target name
...

plugins - An array of plugins in the document
...


History Object

JavaScript History Object
The JavaScript History Object is property of the window object
...

length - The number of entries in the history object
...

previous - The URL of the last document in the history object
...
This does the same
thing as the browser back button
...
back()">


Here is the button:
Go Back

forward()- Go to the next URL entry in the history list
...
This is only effective when
there is a next document in the history list
...

The following HTML code creates a forward button:

onClick="history
...
If an
integer is used, the browser will go forward or back (if the value is
negative) the number of specified pages in the history object (if the
requested entry exists in the history object)
...

onClick="history
...


Navigator Object

Navigator Object

The Navigator object is actually a JavaScript object, not an HTML DOM
object
...


Navigator Object Collections
Collection
plugins[]

Description
Returns a reference to all embedded objects in the
document

Navigator Object Properties
Property
appCodeName
appMinorVersion
AppName
appVersion
browserLanguage
cookieEnabled
CpuClass
Online
Platform
systemLanguage
UserAgent
userLanguage

Description
Returns the code name of the browser
Returns the minor version of the browser
Returns the name of the browser
Returns the platform and version of the browser
Returns the current browser language
Returns a Boolean value that specifies whether
cookies are enabled in the browser
Returns the CPU class of the browser's system
Returns a Boolean value that specifies whether the
system is in offline mode
Returns the operating system platform
Returns the default language used by the OS
Returns the value of the user-agent header sent by
the client to the server
Returns the OS' natural language setting

Navigator Object Methods
Method
javaEnabled()
taintEnabled()

 12
...
This
corresponds to an HTML input form constructed with the FORM tag
...


Form Object Properties


action - This specifies the URL and CGI script file name the form is to
be submitted to
...










elements - An array of fields and elements in the form
...
It specifies the encoding method
the form data is encoded in before being submitted to the server
...
The default is
"application/x-www-form-urlencoded"
...

length - The number of fields in the elements array
...
E
...

method - This is a read or write string
...

name - The form name
...

target - The name of the frame or window the form submission response
is sent to by the server
...


Form Objects
Forms have their own objects
...
Methods are click(), blur(), and
focus()
...
In this case, "button"
...

checkbox - An GUI check box control
...
Attributes:
checked - Indicates whether the checkbox is checked
...

defaultChecked - Indicates whether the checkbox is checked by default
...

name - The name of the checkbox
...

value - A read or write string that specifies the value returned when the
checkbox is selected
...
This is the
same as the text element with the addition of a directory browser
...
Attributes:
name - The name of the FileUpload object
...

value - The string entered which is returned when the form is submitted
...
No methods exist for this object
...


o
o

o
o
o
o

o
o
o
o
o
o

o
o
o

o
o
o
o
o

o
o
o

o
o

type - Type is "hidden"
...

password - A text field used to send sensitive data to the server
...
Attributes:
defaultValue - The default value
...
"
type - Type is "password"
...

radio - A GUI radio button control
...
Attributes:
checked - Indicates whether the radio button is checked
...

defaultChecked - Indicates whether the radio button is checked by
default
...

length - The number of radio buttons in a group
...

type - Type is "radio"
...

reset - A button object used to reset a form back to default values
...
Attributes:
name - The name of the reset object
...

value - The text that appears on the button
...

select - A GUI selection list
...
Methods
are blur(), and focus()
...

name - The name of the selection list
...

selectedIndex - Specifies the current selected option within the select list
type - Type is "select"
...
Methods are click(), blur(), and focus()
...

type - Type is "submit"
...

text - A GUI text field object
...

Attributes:
defaultValue - The text default value of the text field
...


o
o

o
o
o
o

type - Type is "text"
...
It is sent to
the server when the form is submitted
...
Methods are blur(), focus(), and
select()
...

name - The name of the text area
...

value- The text that is entered and appears in the text area field
...


Form Object Methods



reset() - Used to reset the form elements to their default values
...


Events



onReset
onSubmit

 13
...

Events

By using JavaScript, we have the ability to create dynamic web pages
...

Every element on a web page has certain events which can trigger
JavaScript functions
...
We define the events in the HTML tags
...
It is fired when client side image map
area or document is clicked
...

Ondblclick event is also a link
...
It is also a click event
...

The onload event is often used to check the visitor's browser type and
browser version, and load the proper version of the web page based on
the information
...
For
example, you could have a popup asking for the user's name upon his
first arrival to your page
...
Next time
the visitor arrives at your page, you could have another popup saying
something like: "Welcome John Doe!"
...

Below is an example of how to use the onChange event
...

The onkeydown event is fired when a user presses the key
...

All the events are known as the keyboard events
...


onSelect

It is fired when text is selected in a text field or textarea
...

Below is an example of how to use the onSubmit event
...
If the field values are not accepted, the submit should
be cancelled
...
If it
returns true the form will be submitted, otherwise the submit will be
cancelled:
...
An alert box appears
when an onMouseMove event is detected:
onMouseMove="alert('An onMouseMove event');return false">

The setTimeout() method returns a value - In the statement above, the
value is stored in a variable called t
...

The first parameter of setTimeout() is a string that contains a JavaScript
statement
...

The second parameter indicates how many milliseconds from now you
want to execute the first parameter
...

Example

When the button is clicked in the example below, an alert box will be
displayed after 5 seconds
...
In the example below, when the button is clicked, the input
field will start to count (for ever), starting at 0:






onClick="timedCount()">





clearTimeout()
Syntax
clearTimeout(setTimeout_variable)
Example

The example below is the same as the "Infinite Loop" example above
...
getElementById('txt')
...
Its original
name is “personal home page”
...

PHP is the widely used, free, and efficient alternative to
competitors such as Microsoft's ASP
...

The PHP syntax is very similar to Perl and C
...

It also supports ISAPI and can be used with Microsoft's IIS on
Windows
...
Scripts in
a PHP file are executed on the server
...
)
PHP is an open source software (OSS)
PHP is free to download and use






What is a PHP File?
PHP files may contain text, HTML tags and scripts
PHP files are returned to the browser as plain HTML
PHP files have a file extension of "
...
php3", or "
...
)
 PHP is compatible with almost all servers used today (Apache,
IIS, etc
...
php
...
It is an open source software and
doesn’t need to purchase it for development
...
Unlike Java Server Pages or C-based CGI,
PHP doesn’t require you to gain a deep understanding of a
major programming language
...
A lot of it is possible to use PHP just by modifying freely
available scripts rather than writing
3) HTML-embedded ness
PHP is embedded within HTML
...

When a client requests this page, the Web server
preprocesses it
...
For one thing, the parser will suck up all assigned
variables (marked by dollar signs) and try to plug them into
later PHP commands (in this case, the echo function)
...

A huge percentage of the world’s HTTP servers run on one of
these two classes of operating systems
...
k
...
i
Planet Server)
...

5) Not tag-based
PHP is a real programming language
...
In PHP, you can define functions
t just by typing a name and a definition
...

The software doesn’t change radically and incompatibly from release to
release
...

7) Speed





PHP is pleasingly zippy in its execution, especially when
compiled as an Apache module on the Unix side
...

PHP5 is much faster for almost every use than CGI scripts
...
” Although many CGI scripts are
written Although it takes a slight performance hit by being
interpreted rather than compiled, this is far outweighed by the
benefits PHP derives from its status as a Web server module
...
php files in your web directory - and the
server will parse them for you
...

However, if your server does not support PHP, you must install
PHP
...
net on how to
install PHP5:
http://www
...
net/manual/en/install
...
php
...
php
Download MySQL Database
Download
MySQL
for
free
http://www
...
com/downloads/index
...
apache
...
cgi

here:
here:
here:

PHP Syntax
Basic PHP Syntax
A PHP scripting block always starts with ?>
...

On servers with shorthand support enabled you can start a
scripting block with
...


?>
A PHP file normally contains HTML tags, just like an HTML file,
and some PHP scripting code
...
The
semicolon is a separator and is used to distinguish one set of
instructions from another
...
In the example above we have used the echo
statement to output the text "Hello World"
...



//This is a comment
/*
This is
a comment
block
*/
?>


Some important things to know when scripting with php

2) PHP Configuration



Overview
Using this installation gude you can:





create different PHP
...

Pre-installation notices
The directory layout is described in the Array article
...

You can change the name of the folder with PHP installed to
something like PHP, PHP5, PHP-5
...
8, etc
...
2 in the commands below
...

Download and unpack
Download PHP ZIP package from Array into the
C:WITSuitePackages folder
...
2
...
2
...
zip

Unpack it to the C:WITSuiteLanguagesPHP-5
...

Continue with PHP configuration and integration
...

Continue with Configure PHP to use in command prompt,
Configure Apache Service, or Configure IIS FastCGI
...
2wsdl
C:WITSuiteTemporaryFilesPHP-5
...
2upload
Copy the C:WITSuiteLanguagesPHP-5
...
ini-recommended to
C:WITSuiteConfigurationPHP-5
...
ini
...
2php
...
wsdl_cache_dir="C:WITSuiteTemporaryFilesPHP5
...
save_path="C:WITSuiteTemporaryFilesPHP5
...
2upload"
display_errors=On
extension_dir="C:WITSuiteLanguagesPHP-5
...
Sample list of frequently used
extensions:
extension=php_mbstring
...
dll
extension=php_pdo_mysql
...
dll
extension=php_mysql
...
dll
extension=php_sqlite
...
dll

Create the C:WITSuiteShortcutsPHP-5
...
bat file with the
following content:
@echo off
set PATH=%PATH%;C:WITSuiteLanguagesPHP-5
...
2
C:WITSuiteLanguagesPHP-5
...
exe %*

Execute in the Array the following command to test the PHP
command line interface:

C:WITSuiteShortcutsPHP-5
...
bat -i | more

Configure Apache Service
Create folders:






C:WITSuiteConfigurationApache-2
...
2
C:WITSuiteTemporaryFilesApache-2
...
2
C:WITSuiteTemporaryFilesApache-2
...
2wsdl
C:WITSuiteTemporaryFilesApache-2
...
2sessions
C:WITSuiteTemporaryFilesApache-2
...
2upload
Copy the C:WITSuiteConfigurationPHP-5
...
ini file to
C:WITSuiteConfigurationApache-2
...
2php
...

Change the following settings in the
C:WITSuiteConfigurationApache-2
...
2php
...
wsdl_cache_dir="C:WITSuiteTemporaryFilesApache2
...
2wsdl"
session
...
2PHP-5
...
2PHP-5
...
2httpd
...
Add ScriptAlias and Action directives:
ScriptAlias /php-5
...
2/"
Action application/x-httpd-php-5
...
2/php-cgi
...
Add AddType directive for the PHP file extension:
AddType application/x-httpd-php-5
...
php

3
...
2">
SetEnv PHPRC "C:WITSuiteConfigurationApache-2
...
2"
SetEnv PATH
"C:WINDOWS;C:WINDOWSSystem32;C:WITSuiteLanguagesPHP-5
...
Optionally add index
...
php files if no file specified
...
html index
...
2 service
...
php" file with the following content:
phpinfo();

Opening the "http://localhost:8081/phpinfo
...
Here 8081 is the port on which Apache HTTP
sever listens for incoming requests
...


Configure IIS FastCGI
Following this instruction requires Array on your computer
...
2
C:WITSuiteTemporaryFilesIISPHP-5
...
2wsdl
C:WITSuiteTemporaryFilesIISPHP-5
...
2upload
Copy the C:WITSuiteLanguagesPHP-5
...
ini-recommended to
C:WITSuiteConfigurationIISPHP-5
...
ini
...
2php
...
wsdl_cache_dir="C:WITSuiteTemporaryFilesIISPHP5
...
save_path="C:WITSuiteTemporaryFilesIISPHP5
...
2upload"
display_errors=On
extension_dir="C:WITSuiteLanguagesPHP-5
...
impersonate=1
cgi
...
force_redirect=0
Enable necessary extensions
...
1 (Windows XP) or 6
...
2" folder and modification
permissions on the "C:WITSuiteTemporaryFilesIIS" folder
to the "IWAM_[COMPUTERNAME]" user and the
"IUSR_[COMPUTERNAME]" user
...
ini as
follows:


Add the php extension to the Types group
...

php=PHP-5
...




Create the PHP-5
...
2]
ExePath=C:WITSuiteLanguagesPHP-5
...
exe
Arguments=-c C:WITSuiteConfigurationIISPHP-5
...
ini
QueueLength=999
MaxInstances=20
InstanceMaxRequests=500
ActivityTimeout=500

Open IIS Management Console and register application
mapping for the php extension:
1
...

2
...

button
...
Click Add on the Mappings tab, browse for
C:WINDOWSsystem32inetsrvfcgiext
...
php", set Limit to "GET,HEAD,POST", check
Script engine, and then click Ok
...
Click Ok in the Default Web Site Properties dialog
...

Continue with Array

Configure IIS 7 (Windows Vista SP1
and Windows Server 2008)
Grant read permissions on the
"C:WITSuiteConfigurationIIS" folder and the
"C:WITSuiteLanguagesPHP-5
...

You can create PHP handler with IIS Manager or with the
appcmd command
...

Search for the Administrative Tools menu item and click
on it or select System and Maintenance and click on the
Administrative Tools item
...

Open Handler Mappings
...
on the Actions panel
...
php
Module: FastCgiModule
Executable: C:WITSuiteLanguagesPHP-5
...
exe|-c
C:WITSuiteConfigurationIISPHP-5
...
ini
Name: FastGCI-PHP-5
...
Confirm the the action by clicking on
the "Ok" button in confirmation dialog
...

Continue with Array
Configure using the appcmd command
Open the command prompt and execute the following
commands:





%SystemRoot%system32inetsrvappcmd set config
/section:system
...
2php-cgi
...
2php
...
webServer/handlers "/+[name='FastGCI-PHP5
...
php',verb='*',modules='FastCgiModule',scriptProcessor='C
:WITSuiteLanguagesPHP-5
...
exe|-c
C:WITSuiteConfigurationIISPHP5
...
ini',responseBufferLimit='0',resourceType='Either']"

Optionaly, add index
...
webServer/defaultDocument
/+files
...
php']
Continue with Array

Testing your configuration
To test whether the PHP engine is installed successfully,
create in the "C:inetpubwwwroot" folder the "phpinfo
...
php" URL in the
browser should display the information about PHP
configuration
...

Variables in PHP
All variables in PHP start with a $ sign symbol
...








All variables in PHP are denoted with a leading dollar sign ($)
...

Variables are assigned with the = operator, with the variable
on the left- hand side and the expression to be evaluated on
the right
...

Variables have no intrinsic type other than the type of their
current value
...

Below, the PHP script assigns the string "Hello World" to a
variable called $txt:


$txt="Hello World";
echo $txt;
?>


To concatenate two or more variables together, use the dot (
...
$txt2 ;
?>


The output of the script above will be: "Hello World 1234"
...
If a variable name
should be more than one word, it should be separated with
underscore ($my_string), or with capitalization ($myString)
Variable scope




The scope of a variable is the context within which it is
defined
...

This single scope spans included and required files as well
Example:
$a = 1;
include 'b
...
inc
script
...
Any variable used inside a function is by default
limited to the local function scope
...
You may
notice that this is a little bit different from the C language in
that global variables in C are automatically available to
functions unless specifically overridden by a local definition
...

The global keyword



In PHP global variables must be declared global inside a
function if they are going to be used in that function
...

There is no limit to the number of global variables that can be
manipulated by a function
...
The previous
example can be rewritten as:
Example Using $GLOBALS instead of global
$a = 1;

$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of
the global variable being the key and the contents of that
variable being the value of the array element
...
Here's an example demonstrating the power of
superglobals:
Example demonstrating superglobals and scope
function test_global()
{
// Most predefined variables aren't "super" and require
// 'global' to be available to the functions local scope
...
Superglobals are available
// as of PHP 4
...
0, and HTTP_POST_VARS is now
// deemed deprecated
...

A static variable exists only in a local function scope, but it
does not lose its value when program execution leaves this
scope
...
The $a++ which increments the
variable serves no purpose since as soon as the function exits
the $a variable disappears
...

Static variables also provide one way to deal with recursive
functions
...
Care
must be taken when writing a recursive function because it is
possible to make it recurs indefinitely
...
The
following simple function recursively counts to 10, using the
static variable $count to know when to stop:
Static variables with recursive functions
function test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>

Note: Static variables may be declared as seen in the
examples above
...

Example 7 Declaring static variables
function foo(){
static $int = 0;
// correct
static $int = 1+2;
// wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
?>

Variable variables
...
A normal variable is set with a statement such
as:
$a = 'hello';
?>



A variable variable takes the value of a variable and treats
that as the name of a variable
...
i
...

$$a = 'world';
?>



At this point two variables have been defined and stored in the
PHP symbol tree: $a with contents "hello" and $hello with
contents "world"
...
e
...

GET & POST Method:
There are two ways the browser client can send information to
the web server
...
In this scheme, name/value pairs
are joined with equal signs and different pairs are separated by
the ampersand
...
After the information is encoded it is sent to
the server
...
The page and the encoded
information are separated by the ? character
...
test
...
htm?name1=value1&name2=value2



The GET method produces a long string that appears in your
server logs, in the browser's Location: box
...




Never use GET method if you have password or other sensitive
information to be sent to the server
...




The data sent by GET method can be accessed using
QUERY_STRING environment variable
...

Try out following example by putting the source code in test
...

if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome "
...
"
";
echo "You are "
...
" years old
...

The information is encoded as described in case of GET method
and put into a header called QUERY_STRING
...




The POST method can be used to send ASCII as well as binary
data
...
By using Secure HTTP you
can make sure that your information is secure
...

Try out following example by putting the source code in test
...

if( $_POST["name"] || $_POST["age"] )
{

echo "Welcome "
...
"
";
echo "You are "
...
" years old
...

Arithmetic Operators
Arithmetic Operators

Example

Name

Result

-$a

Negation

Opposite of $a
...


$a - $b

Subtraction

Difference of $a and $b
...


$a / $b

Division

Quotient of $a and $b
...







The division operator ("/") returns a float value unless the two
operands are integers (or strings that get converted to
integers) and the numbers are evenly divisible, in which case
an integer value will be returned
...

Remainder $a % $b is negative for negative $a
...


$a++

Post-increment

Returns $a, then increments $a by
one
...


$a--

Post-decrement

Returns $a, then decrements $a by
one
...
$a++
...
$a
...
++$a
...
$a
...
$a--
...
$a
...
--$a
...
$a
...
For example, in
Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' (
ord('Z') == 90, ord('[') == 91 )
...

Example 1 Arithmetic Operations on Character Variables
$i = 'W';
for ($n=0; $n<6; $n++) {
echo ++$i
...

Assignment Operators
Operator
=
+=
-=
*=
/=
%=

Example
x=y
x+=y
x-=y
x*=y
x/=y
x%=y

Is The Same As
x=y
x=x+y
x=x-y
x=x*y
x=x/y
x=x%y

Comparison Operators
Comparison operators, as their name implies, allow you to
compare two values
...


Comparison Operators
Example

Name

Result

$a== $b

Equal

$a===
$b

Identical

$a != $b

Not
equal

TRUE

if $a is not equal to $b
...


$a!==$b

Not
identical

$a < $b

Less
than

TRUE

if $a is strictly less than $b
...


$a<= $b

Less
than or
equal to

TRUE

if $a is less than or equal to $b
...


TRUE

if $a is equal to $b
...
(introduced in PHP 4)
TRUE

if $a is not equal to $b, or they are not of
the same type
...
If you compare two numerical strings,
they are compared as integers
...

var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>

Logical Operators
Logical Operators
Example

Name

Result

$a and $b

And

TRUE if both $a and $b are TRUE
...


$a xor $b

Xor

TRUE if either $a or $b is TRUE, but not both
...


$a && $b

And

TRUE if both $a and $b are TRUE
...


The reason for the two different variations of "and" and "or"
operators is that they operate at different precedence
...
For example, in the expression 1 +
5 * 3, the answer is 16 and not 18 because the multiplication
("*") operator has a higher precedence than the addition ("+")
operator
...
For instance: (1 + 5) * 3 evaluates to 18
...

The following table lists the precedence of operators with the
highest-precedence operators listed at the top of the table
...


Operator Precedence
Associativity

Operators

Additional
Information

non-associative

clone new

clone and new

Left

[

array()

non-associative

++ --

increment/decrement

non-associative

~ - (int) (float) (string)
(array) (object) (bool) @

types

non-associative

instanceof

types

right

!

logical

Left

*/%

arithmetic

Left

+-
...
= %= &=
|= ^= <<= >>=

assignment

Left

and

logical

Left

xor

logical

Left

or

logical

Left

,

many uses

Left Associativity means that the expression is evaluated from
left to right, right associativity means the opposite
...

String Operators
There are two string operators
...
'), which returns the concatenation of its right and
left arguments
...
='), which appends the argument on the right side
to the argument on the left side
...


$a = "Hello
$b = $a
...
= "World!";
// now $a contains "Hello World!"
?>



print_r — Prints human-readable information about a
variable
syntax:
mixed print_r ( mixed $expression [, bool $return ] )
print_r() displays information about a variable in a way that's
readable by humans
...
Static
class members will not be shown
...
Use reset() to bring it back to beginning
...

return

If you would like to capture the output of print_r(), use the
return parameter
...

Return Values
If given a string, integer or float, the value itself will be
printed
...
Similar notation is used for
objects
...
It allows for conditional execution of
code fragments
...

If expression evaluates to TRUE, PHP will execute statement,
and if it evaluates to FALSE - it'll ignore it
...

If_else statement
Often you'd want to execute a statement if a certain condition
is met, and a different statement if the condition is not met
...
else extends an if statement to
execute a statement in case the expression in the if statement
evaluates to FALSE
...

Like else, it extends an if statement to execute a different
statement in case the original if expression evaluates to
FALSE
...
For example, the following code would display a is
bigger than b, a equal to b or a is smaller than b:
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

There may be several elseifs within the same if statement
...
In PHP, you can also write 'else if' (in two words)
and the behavior would be identical to the one of 'elseif' (in a
single word)
...

The elseif statement is only executed if the preceding if
expression and any preceding elseif expressions evaluated to
FALSE, and the current elseif expression evaluated to TRUE
...
In many occasions, you may want to
compare the same variable (or expression) with many
different values, and execute a different piece of code
depending on which value it equals to
...

$i=2;
switch ($i)
{
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>

 Looping:

while
while loops are the simplest type of loop in PHP
...
The basic form of a while
statement is:
while (expr)
statement





The meaning of a while statement is simple
...

The value of the expression is checked each time at the
beginning of the loop, so even if this value changes during the
execution of the nested statement(s), execution will not stop
until the end of the iteration (each time PHP runs the
statements in the loop is one iteration)
...

Like with the if statement, you can group multiple statements
within the same while loop by surrounding a group of
statements with curly braces, or by using the alternate
syntax:
while (expr):
statement

...

The main difference from regular while loops is that the first
iteration of a do-while loop is guaranteed to run (the truth
expression is only checked at the end of the iteration),
whereas it may not necessarily run with a regular while loop
(the truth expression is checked at the beginning of each
iteration, if it evaluates to FALSE right from the beginning, the
loop execution would end immediately)
...

Advanced C users may be familiar with a different
the do-while loop, to allow stopping execution in the
code blocks, by encapsulating them with do-while
using the break statement
...
They behave like
their C counterparts
...

In the beginning of each iteration, expr2 is evaluated
...
If it evaluates to FALSE, the
execution of the loop ends
...

Each of the expressions can be empty or contain multiple
expressions separated by commas
...
expr2 being empty means the loop should
be run indefinitely (PHP implicitly considers it as TRUE, like C)
...

Consider the following examples
...
foreach
works only on arrays, and will issue an error when you try to
use it on a variable with a different data type or an
uninitialized variable
...

On each loop, the value of the current element is assigned to
$value and the internal array pointer is advanced by one (so
on the next loop, you'll be looking at the next element)
...





break
break ends execution of the current for, foreach, while, dowhile or switch structure
...

break;

/* You could also write 'break 1;' here
...
*/
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5
\n";
break 1; /* Exit only the switch
...
*/
default:
break;
}
}
?>



continue
continue is used within looping structures to skip the rest of
the current loop iteration and continue execution at the
condition evaluation and then the beginning of the next
iteration
...

continue accepts an optional numeric argument which tells it
how many levels of enclosing loops it should skip to the end
of
...

\n";
} echo "Neither does this
...

A map is a type that associates values to keys
...
As array values can be other arrays, trees
and multidimensional array are also possible
...
It
takes as parameters any number of comma-separated key =>
value pairs
...

)
// key may only be an integer or string
// value may be any value of any type
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>

A key may be either an integer or a string
...
e
...
Floats in key are truncated to integer
...

A value can be any PHP type
...
If a key that already has an assigned value is specified, that
value will be overwritten
...

array(5 => 43, 32, 56, "b" => 12);
//
...

This is done by assigning values to the array, specifying the
key in brackets
...

$arr[key] = value;
$arr[] = value;
// key may be an integer or string

// value may be any value of any type
If $arr doesn't exist yet, it will be created, so this is also an
alternative way to create an array
...
To remove a
key/value pair, call the unset() function on it
...

$array = array(1, 2, 3, 4, 5);
print_r($array);
// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5, instead of 0)
...
Otherwise it will output "Have a nice
day!":


$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>


The Switch Example
Example


switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";

break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>


When working with PHP, sooner or later, you might want to
create many similar
...

In PHP - there are more than 700 built-in functions available
...
You can
produce interesting and useful Web sites simply with the basic
language constructs and the large body of built-in functions
...


What is a function?
A function is a way of wrapping up a chunk of code and giving
that chunk a name, so that you can use that chunk later in
just one line of code
...


Function definition syntax
Function definitions have the following form:
function function-name ($argument-1, $argument-2,
...

}
function definitions have four parts:





The special word function
The name that you want to give your function
The function’s parameter list—dollar-sign variables separated
by commas
The function body—a brace-enclosed set of statements
Function naming rule




Just as with variable names, the name of the function must be
made up of letters, numbers and underscores, and it must not
start with a number
...

Create a PHP Function
A function is a block of code that can be executed whenever
we
need
it
...
The name can start with a
letter or underscore (not a number)
Add a "{" - The function code starts after the opening curly
brace
Insert the function code
Add a "}" - The function is finished by a closing curly brace

Example
A simple function that writes my name when it is called:


function writeMyName()
{
echo "Kai Jim Refsnes";
}
writeMyName();
?>


Use a PHP Function
Now we will use the function in a PHP script:


function writeMyName()
{
echo "Kai Jim Refsnes";
}
echo "Hello world!
";
echo "My name is ";
writeMyName();
echo "
...
";
?>


The output of the code above will be:
Hello world!
My name is Kai Jim Refsnes
...


PHP Functions - Adding parameters
Our first function (writeMyName()) is a very simple function
...

To add more functionality to a function, we can add
parameters
...

You may have noticed the parentheses after the function
name, like: writeMyName()
...

Example 1
The following example will write different first names, but the
same last name:


function writeMyName($fname)
{
echo $fname
...

";
}
echo "My name is ";
writeMyName("Kai Jim");
echo "My name is ";
writeMyName("Hege");
echo "My name is ";
writeMyName("Stale");
?>


The output of the code above will be:
My name is Kai Jim Refsnes
...

My name is Stale Refsnes
...
" Refsnes"
...
"
";
}
echo "My name is ";
writeMyName("Kai Jim","
...
");
?>


The output of the code above will be:
My name is Kai Jim Refsnes
...

PHP Functions - Return values
Functions can also be used to return values
...
add(1,16)
?>


The output of the code above will be:

1 + 16 = 17

8) Variable Length Argument list



 Php support for variable-length argument list in user defined
function
...

 No special syntax is required, and argument list may still be
explicitly provided with function definitions and will behave as
normal



func_num_args — Returns the
arguments passed to the function

number

of

syntax:
int func_num_args ( void )



Gets the number of arguments passed to the function
...

Return Values
Returns the number of arguments passed into the current
user-defined function
...

This function may be used in conjunction with func_get_args()
and func_num_args() to allow user-defined functions to accept
variable-length argument lists
...
Function arguments are counted starting
from zero
...

Examples
Example 1 func_get_arg() example
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs
\n";
if ($numargs >= 2) {
echo "Second argument is: "
...
"
\n";
}
}
foo (1, 2, 3);
?>



func_get_args — Returns an array comprising a
function's argument list
syntax:
array func_get_args ( void )




Gets an array of the function's argument list
...

Return Values
Returns an array in which each element is a copy of the
corresponding member of the current user-defined function's
argument list
...
func_get_arg(1)
...
$arg_list[$i]
...

Possibles values for the returned string are:











"boolean"
"integer"
"double" (for historical reasons "double" is returned in case of
a
float, and not simply "float")
"string"
"array"
"object"
"resource"
"NULL"
"unknown type"
Examples
Example 1 gettype() example

$data = array(1, 1
...

Parameters
var
The variable being converted
...
2
...
2
...
2
...
2
...

Examples
Example 1 settype() example
$foo = "5bar"; // string

$bar = true;

// boolean

settype($foo, "integer"); // $foo is now 5 (integer)
settype($bar, "string"); // $bar is now "1" (string)
?>



Isset- Determine if a variable is set and is not NULL
Sysntax:
bool isset ( mixed $var [, mixed $var [, $
...

If a variable has been unset with unset(), it will no longer be
set
...
Also note that a NULL byte ("\0") is not
equivalent to the PHP NULL constant
...
Evaluation goes
from left to right and stops as soon as an unset variable is
encountered
...

Example #1 isset()
$var = '';
// This will evaluate to TRUE so the text will be printed
...
";
}
// In the next examples we'll use var_dump to output
// the return value of isset()
...
See the documentation on
string for more information on converting to string
...

may be any scalar type
...

var

Return Values
The string value of var
...

Parameters
var

May be any scalar type
...

Return Values
The float value of the given variable
...
34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122
...

Parameters
var

The scalar value being converted to an integer
base

The base for the conversion (default is base 10)
Return Values
The integer value of var on success, or 0 on failure
...

The maximum value depends on the system
...
So for example on such a system,
intval('1000000000000')
will return 2147483647
...


Strings will most likely return 0 although this depends on the
leftmost characters of the string
...

Examples
Example 1 intval() examples
The following examples are based on a 32 bit system
...
2);
// 4
echo intval('42');
// 42
echo intval('+42');
// 42
echo intval('-42');
// -42
echo intval(042);
// 34
echo intval('042');
// 42
echo intval(1e10);
// 1410065408
echo intval('1e10');
// 1
echo intval(0x1A);
// 26
echo intval(42000000);
// 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);
// 42
echo intval('42', 8);
// 34
?>



print_r — Prints human-readable information about
a variable
syntax:

mixed print_r ( mixed $expression [, bool $return ] )
print_r() displays information about a variable in a way that's
readable by humans
...
Static
class members will not be shown
...
Use reset() to bring it back to beginning
...

return

If you would like to capture the output of print_r(), use the
return parameter
...


Return Values
If given a string, integer or float, the value itself will be
printed
...
Similar notation is used for
objects
...
]] )
unset() destroys the specified variables
...

If a globalized variable is unset() inside of a function, only
the local variable is destroyed
...


function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>

The above example will output:
bar
If you would like to unset() a global variable inside of a
function, you can use the $GLOBALS array to do so:
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>



If a variable that is PASSED BY REFERENCE is unset() inside
of a function, only the local variable is destroyed
...

function foo(&$bar)
{
unset($bar);
$bar = "blah";
}
$bar = 'something';
echo "$bar\n";
foo($bar);
echo "$bar\n";
?>

The above example will output:
something
something


If a static variable is unset() inside of a function, unset()
destroys the variable only in the context of the rest of a
function
...

function foo()
{
static $bar;
$bar++;
echo "Before unset: $bar, ";
unset($bar);
$bar = 23;
echo "after unset: $bar\n";
}
foo();
foo();
foo();
?>

The above example will output:
Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

10) String Function






A string is series of characters
...
That is, there are
exactly 256 different characters possible
...

It is no problem for a string to become very large
...

A string literal can be specified in four different ways:
- Single quoted
- Double quoted






- Heredoc syntax
Single quoted
The simplest way to specify a string is to enclose it in single
quotes (the character ')
...

If a backslash needs to occur before a single quote, or at the
end of the string, you need to double it (\\)
...


example
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*
...
*?';
// Outputs: You deleted C:\*
...
*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>



Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret
more escape sequences for special characters:
Escaped characters

Sequence

Meaning

\n

linefeed (LF or 0x0A (10) in ASCII)

\r

carriage return (CR or 0x0D (13) in ASCII)

Escaped characters
Sequence

Meaning

\t

horizontal tab (HT or 0x09 (9) in ASCII)

\v

vertical tab (VT or 0x0B (11) in ASCII) (since PHP
5
...
5)

\f

form feed (FF or 0x0C (12) in ASCII) (since PHP
5
...
5)

\\

Backslash

\$

dollar sign

\"

double-quote

\[0-7]{1,3}

the sequence of characters matching the regular
expression is a character in octal notation

\x[0-9A-Faf]{1,2}

the sequence of characters matching the regular
expression is a character in hexadecimal notation






As in single quoted strings, escaping any other character will
result in the backslash being printed too
...

Heredoc
Another way to delimit strings is the heredoc syntax: <<<
...

The closing identifier must begin in the first column of the line
...

It especially useful in creating pages that contains HTML
forms
...

EOD;
echo $db;

echo $sing;
echo $str;
?>



chr
- Returns a one-character string containing the character
specified by ascii
...

Syntax:

int ord ( string $string )

Example:
Echo ord(“A”);
//65
Echo ord(“abc”); //97



strtolower
- Returns string with all alphabetic characters converted to
lowercase
...

Syntax:

string strtoupper ( string $string )

Example:
echo strtoupper(“WelCome To HNS”);
TO HNS



//

WELCOME

strlen
- Returns the length of the given string
...


(or

other

characters)

from

the

Syntax:
string ltrim ( string $str [, string $charlist ] )
This function returns a string with whitespace stripped from
the beginning of str
...

"\t" (ASCII 9 (0x09)), a tab
...

"\r" (ASCII 13 (0x0D)), a carriage return
...

"\x0B" (ASCII 11 (0x0B)), a vertical tab
...
Simply list all characters that

you want to be stripped
...
you can specify a range of
characters
...

Syntax:
String rtrim ( string $str [, string $charlist ] )
Example:
echo rtrim(“__HNS__”);
echo rtrim(“__welcome”);
echo rtrim(“hns__”);



//__HNS
//__welcome
//hns

trim
-Strip whitespace (or other characters) from the beginning
and end of a string
...

Syntax:
string trim ( string $str [, string $charlist ] )
Example:
echo rtrim(“__HNS__”);
echo rtrim(“__welcome”);
echo rtrim(“hns__”);



substr

//HNS
//welcome
//hns

- Returns the portion of string specified by the start and
parameters
...




For instance, in the string 'abcdef', the character at position 0
is 'a', the character at position 2 is 'c', and so forth
...




If string is less than or equal to start characters long, FALSE will
be returned
...




If length is given and is negative, then that many characters
will be omitted from the end of string (after the start position
has been calculated when a start is negative)
...

Example # 2
$rest =
$rest =
$rest =
$rest =
?>

substr("abcdef",
substr("abcdef",
substr("abcdef",
substr("abcdef",

echo substr('abcdef',
echo substr('abcdef',
echo substr('abcdef',
echo substr('abcdef',
echo substr('abcdef',

0, -1); // returns "abcde"
2, -1); // returns "cde"
4, -4); // returns ""
-3, -1); // returns "de"

1);
// bcdef
1, 3); // bcd
0, 4); // abcd
0, 8); // abcdef
-1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];
// a
echo $string[3];
// d
echo $string[strlen($string)-1]; // f
?>

strcmp



- Binary safe string comparison
Syntax:
int strcmp ( string $str1 , string $str2 )



Returns < 0 if str1 is less than str2 ; > 0 if str1 is greater than
str2 , and 0 if they are equal
...

Example:
echo strcmp(“Hello”,”hello”); //-1



strcasecmp
- Binary safe case-insensitive string comparison
Syntax:
int strcasecmp ( string $str1 , string $str2 )
Returns < 0 if str1 is less than str2 ; > 0 if str1 is greater than
str2 , and 0 if they are equal
...
Unlike the strrpos(), this function can take
a full string as the needle parameter and the entire string will
be used
...

The optional offset parameter allows you to specify which
character in haystack to start searching
...

Example:
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a'); // $pos = 0
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

strrpos



- Find position of last occurrence of a char in a string
Syntax:
int strrpos ( string $haystack , string $needle [, int $offset ]
)




Returns the numeric position of the last occurrence of needle in
the haystack string
...
If a string is passed as the
needle, then only the first character of that string will be used
...

Example
$nstr=’abcdef abcdef’;
$pos=strrpos($nstr,’a’);

//$pos=7



strstr
- Find first occurrence of a string
Syntax:
string strstr ( string $haystack , mixed $needle [, bool
$before_needle ] )
Returns part of haystack string from the first occurrence of
needle to the end of haystack
...
For case-insensitive searches,
use stristr()
...

needle :If needle is not a string, it is converted to an integer and
applied as the ordinal value of a character
...

Return Values
Returns the portion of string, or FALSE if needle is not found
...
com';
$domain = strstr($email, '@');
echo $domain; // prints @example
...
3
...

Syntax:
string stristr ( string $haystack , mixed $needle [, bool
$before_needle ] )
Parameters
Haystack:The string to search in
needle :If needle is not a string, it is converted to an integer
and applied as the ordinal value of a character
...


needle



and haystack are examined in a case-insensitive manner
...
If needle is not found, returns
FALSE
...
com';
echo stristr($email, 'e'); // outputs ER@EXAMPLE
...
3
...

If replace has fewer values than search , then an empty string is
used for the rest of replacement values
...
The
converse would not make sense, though
...

Example
// Provides:
$bodytag = str_replace("%body%", "black", "");
// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day
...
0
...

Parameters: string :The string to be reversed
...

Example
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

echo



- Output one or more strings
Syntax:
void echo ( string $arg1 [, string $
...

echo() is not actually a function (it is a language construct),
so you are not required to use parentheses with it
...

Additionally, if you want to pass more than one parameter to
echo(), the parameters must not be enclosed within
parentheses
...
The newlines will be
output as well";
echo "This spans\nmultiple lines
...
";
echo "Escaping characters is done \"Like this\"
...
This
short syntax only works with the short_open_tag configuration
setting enabled
...


print



- Output a string
Syntax:
int print ( string $arg )




Outputs arg
...

print() is not actually a real function (it is a language
construct) so you are not required to use parentheses with its
argument list
...
";
print "This spans
multiple lines
...
The newlines will be\noutput as well
...
";

Diffrence between print() and echo()
1
...

echo “Hello”,”How R U?”
//valid
echo “Hello”,”How R U?”
//invalid
2
...
The value return 1 if
the printing was successfully and o if unsuccessfuly
...

If the argument number is of type float, the return type is also
float, otherwise it is integer (as float usually has a bigger
value range than integer)
...
2); // $abs = 4
...

The return value of ceil() is still of type float as the value
range of float is usually bigger than that of integer
...
3); // 5
echo ceil(9
...
14); // -3
?>



floor
floor — Round fractions down
Syntax
float floor ( float $value )




Returns the next lowest integer value by rounding down value
if necessary
...

Examples
echo floor(4
...
999); // 9
echo floor(-3
...

precision can also be negative or zero (default)
...
4);
// 3
echo round(3
...
6);
// 4
echo round(3
...
95583, 2); // 1
...
045, 2); // 5
...
055, 2); // 5
...
The reminder (r) is defined as: x = i *
y + r, for some integer i
...

Examples
$x = 5
...
3;
$r = fmod($x, $y);
// $r equals 0
...
3 + 0
...
7
?>

min



min — Find lowest value
Syntax
mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed
$value3
...

If the first and only parameter is an array, min() returns the
lowest value in that array
...

PHP will evaluate a non-numeric string as 0 if compared to
integer, but still return the string if it's seen as the numerically
lowest value
...

Example
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello');
echo min('hello', 0);
echo min('hello', -1);

// 0
// hello
// -1

// With multiple arrays, min compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
// If both an array and non-array are given, the array
// is never returned as it's considered the largest
$val = min('string', array(2, 5, 7), 42); // string
?>



max
max — Find highest value

Syntax
mixed max ( array $values )
mixed max ( mixed $value1 , mixed $value2 [, mixed $value3
...

If the first and only parameter is an array, max() returns the
highest value in that array
...

PHP will evaluate a non-numeric string as 0 if compared to
integer, but still return the string if it's seen as the numerically
highest value
...

Example
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
echo max(0, 'hello');
echo max('hello', 0);
echo max(-1, 'hello');

// 0
// hello
// hello

// With multiple arrays, max compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)
// If both an array and non-array are given, the array
// is always returned as it's seen as the largest
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)
?>

pow



pow — Exponential expression
Syntax
number pow ( number $base , number $exp )



Returns base raised to the power of exp
...

Examples

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1
echo pow(-1, 5
...
0
...
5); // PHP <=4
...
6 1
...

Examples
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3
...

?>

rand



rand — Generate a random integer
Syntax
int rand ( void )
int rand ( int $min , int $max )


If called without the optional min , max arguments rand()
returns
a
pseudo-random
integer
between
0
and
getrandmax()
...

Examples
echo rand()
...
"\n";
echo rand(5, 15);
?>

The above example will output something similar to:
7771
22264
11

12) Date and time function
The PHP date() function is used to format a time or a date
...

PHP Date - What is a Timestamp?
A timestamp is the number of seconds since January 1, 1970
at 00:00:00 GMT
...

PHP Date - Format the Date
The first parameter in the date() function specifies how to
format the date/time
...
Here are some of the letters that can be used:




d - The day of the month (01-31)
m - The current month, as a number (01-12)
Y - The current year in four digits
Other characters, like"/", "
...
m
...
07
...
In other words, timestamp is optional
and defaults to the value of time()
...
)

The following characters
parameter string
format

character
Day

are

recognized

in

Example
values

Description
---

the

format

returned
---

D

Day of the month, 2 digits
with leading zeros

01 to 31

D

A textual representation of
a day, three letters

Mon through Sun

J

Day of the month without
leading zeros

l
(lowercase
'L')

A full textual representation
of the day of the week

Sunday through
Saturday

N

ISO-8601 numeric
representation of the day of
the week (added in PHP
5
...
0)

1
(for
through
Sunday)

S

English ordinal suffix for the
day of the month, 2
characters

st, nd, rd or th
...
1
...


O

ISO-8601
year number
...
(added in PHP
5
...
0)

Examples:
2003

1999

or

Y

A
full
numeric
representation of a year, 4
digits

Examples:
2003

1999

or

Y

A two digit representation
of a year

Examples: 99 or 03

Time

---

---

The following characters
parameter string

are

recognized

in

the

format

Description

Example
values

A

Lowercase Ante meridiem
and Post meridiem

am or pm

A

Uppercase Ante meridiem
and Post meridiem

AM or PM

B

Swatch Internet time

000 through 999

G

12-hour format of an hour
without leading zeros

1 through 12

G

24-hour format of an hour
without leading zeros

0 through 23

H

12-hour format of an hour
with leading zeros

01 through 12

H

24-hour format of an hour
with leading zeros

00 through 23

I

Minutes with leading zeros

00 to 59

S

Seconds, with leading zeros

00 through 59

U

Microseconds (added in PHP
5
...
2)

Example: 54321

format

character

Timezone

---

returned

---

E

Timezone identifier (added
in PHP 5
...
0)

Examples: UTC, GMT,
Atlantic/Azores

I (capital i)

Whether or not the date is
in daylight saving time

1 if Daylight Saving
Time, 0 otherwise
...
1
...


Z

Timezone offset in seconds
...

Full
Date/Time

---

---

C

ISO 8601 date (added in
PHP 5)

2004-0212T15:19:21+00:00

R

» RFC 2822 formatted date

Example: Thu, 21 Dec
2000 16:01:07 +0200

U

Seconds since the Unix
Epoch (January 1 1970
00:00:00 GMT)

See also time()

Example
echo("Result with date():
");
echo(date("l")
...
"
");
echo("Oct
3,1975
was
on
a
"
...
"
");
echo(date(DATE_RFC822)
...

"/>
");
echo("Result with gmdate():
");
echo(gmdate("l")
...
"
");
echo("Oct
3,1975
was
on
a
"
...
"
");
echo(gmdate(DATE_RFC822)
...
"/>");
?>
The output of the code above could be something like this:
Result with date():
Tuesday
Tuesday 24th of January 2006 02:41:22 PM
Oct 3,1975 was on a Friday

Tue, 24 Jan 2006 14:41:22 CET
1975-10-03T00:00:00+0100
Result with gmdate():
Tuesday
Tuesday 24th of January 2006 01:41:22 PM
Oct 3,1975 was on a Thursday
Tue, 24 Jan 2006 13:41:22 GMT
1975-10-02T23:00:00+0000

The output of the code above could be something like this:
Tomorrow is 2006/07/12



getdate — Get date/time information
syntax:
array getdate ([ int $timestamp ] )



Returns an associative array containing the date information
of the timestamp , or the current local time if no timestamp is
given
...


System Dependent, typically
-2147483648
through
2147483647
...
Checks
the validity of the date formed by the arguments
...

Parameters
month

The month is between 1 and 12 inclusive
...
Leap year s are taken into consideration
...

Examples
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

The above example will output:
bool(true)
bool(false)

 time — Return current Unix timestamp
syntax:
int time ( void )


Returns the current time measured in the number of seconds since
the Unix Epoch (January 1 1970 00:00:00 GMT)
...
date('Y-m-d')
...
date('Y-m-d', $nextWeek)
...
date('Y-m-d', strtotime('+1 week'))
...
This timestamp is a long integer containing the number
of seconds between the Unix Epoch (January 1 1970 00:00:00
GMT) and the time specified
...

Parameters
hour

The number of the hour
...

second

The number of seconds past the minute
...

day

The number of the day
...
On systems where time_t is a 32bit signed
integer, as most common today, the valid range for year is
somewhere between 1901 and 2038
...
1
...
g
...

is_dst

This parameter can be set to 1 if the time is during daylight
savings time (DST), 0 if it is not, or -1 (the default) if it is
unknown whether the time is within daylight savings time or
not
...
This can
cause unexpected (but not incorrect) results
...
If DST is enabled in e
...
2:00, all times
between 2:00 and 3:00 are invalid and mktime() returns an
undefined (usually negative) value
...
g
...

Note: As of PHP 5
...
0, this parameter became deprecated
...

Return Values
mktime() returns the Unix timestamp of the arguments given
...
1 it returned -1)
...
] )




Like array(), this is not really a function, but a language
construct
...

list() only works on numerical arrays and assumes the
numerical indices start at 0
...

Return Values
No value is returned
...
\n";
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power
...


Parameters
var

The variable being evaluated
...

Example
$yes = array('this', 'is', 'an array');
echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";
$no = 'this is a string';
echo is_array($no) ? 'Array' : 'not an Array';
?>

The above example will output:
Array
not an Array



count — Count elements in an array, or properties in an
object
syntax:
int count ( mixed $var [, int $mode ] )



Counts elements in an array, or properties in an object
...
There is one exception, if var is
NULL, 0 will be returned
...

mode

If the optional mode parameter is set to COUNT_RECURSIVE (or
1), count() will recursively count the array
...
The default value for mode is 0
...

Return Values
Returns the number of elements in var , which is typically an
array, since anything else will have one element
...

Use isset() to test if a variable is set
...


 in_array — Checks if a value exists in an array
syntax:
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )


Searches haystack for needle



If needle is a string, the comparison is done in a case-sensitive
manner
...

haystack

The array
...

Return Values:
Returns TRUE if needle is found in the array, FALSE otherwise
...
10', 12
...
13);
if (in_array('12
...
4' found with strict check\n";
}

is

case-

if (in_array(1
...
13 found with strict check\n";
}
?>

The above example will output:
1
...
It advances
the internal array pointer one place forward before returning
the element value
...

Parameters
array

The array being affected
...

This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE, such as 0 or ""
...
Use
the === operator for testing the return value of this function
...

prev() behaves just like next(), except it rewinds the internal
array pointer one place instead of advancing it
...

Return Values:
Returns the array value in the previous place that's pointed to
by the internal array pointer, or FALSE if there are no more
elements
...

Parameters
array

The input array
...

Example
$array = array('step one', 'step two', 'step three', 'step four');
// by default, the pointer is on the first element
echo current($array)
...
"
\n"; // "step three"
// reset pointer, start again on step one
reset($array);
echo current($array)
...

Parameters
array

The array
...


Example
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>



each — Return the current key and value pair from an
array and advance the array cursor
syntax:
array each ( array &$array )



Return the current key and value pair from an array and
advance the array cursor
...
You have to use reset() if you want to
traverse the array again using each
...

Return Values:




Returns the current key and value pair from the array array
...
Elements 0 and key contain the key name
of the array element, and 1 and value contain the data
...

Example
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

Output
Array

(

[1] => bob
[value] => bob
[0] => 0
[key] => 0)
Example
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:
Array
(
[1] => Bob
[value] => Bob
[0] => Robert
[key] => Robert
)
each() is typically used in conjunction with list() to traverse an
array, here's an example:
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>

The above example will output:
a => apple
b => banana
c => cranberry



sort — Sort an array
syntax:

bool sort ( array &$array [, int $sort_flags ] )


This function sorts an array
...

Parameters
array

The input array
...
Added in PHP 4
...
0 and 5
...
2
...

Since
PHP
6,
you
must
use
the
i18n_loc_set_default() function
...

Example
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits["
...
$val
...




rsort — Sort an array in reverse order
syntax:
bool rsort ( array &$array [, int $sort_flags ] )



This function sorts an array in reverse order (highest to lowest)
...
It will
remove any existing keys that may have been assigned, rather than
just reordering the keys
...

sort_flags

You may modify the behavior of the sort using the optional
parameter sort_flags , for details see sort()
...

Example
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The above example will output:
0
1
2
3

=
=
=
=

orange
lemon
banana
apple

The fruits have been sorted in reverse alphabetical order
...
This is used mainly when sorting associative arrays
where the actual element order is significant
...

sort_flags

You may modify the behavior of the sort using the optional
parameter sort_flags , for details see sort()
...

Examples
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" =>
"apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The above example will output:
c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the
index associated with each element has been maintained
...

This is used mainly when sorting associative arrays where the
actual element order is significant
...

sort_flags

You may modify the behavior of the sort using the optional
parameter sort_flags , for details see sort()
...

Example
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" =>
"apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The above example will output:
a = orange
d = lemon
b = banana
c = apple

The fruits have been sorted in reverse alphabetical order, and
the index associated with each element has been maintained
...

]] )





Merges the elements of one or more arrays together so that
the values of one are appended to the end of the previous
one
...

If the input arrays have the same string keys, then the later
value for that key will overwrite the previous one
...

If only one array is given and the array is numerically indexed,
the keys get reindexed in a continuous way
...

array

Variable list of arrays to recursively merge
...

Example
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:
Array
(
[color] => green

[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)



array_reverse — Return an array with elements in reverse
order
syntax:
array array_reverse ( array $array [, bool $preserve_keys ] )


Takes an input array and returns a new array with the order of
the elements reversed
...

preserve_keys

If set to TRUE keys are preserved
...

Examples
$input = array("php", 4
...
The
printout of $result and $result_keyed will be:
Array
(
[0] => Array

(
)

[0] => green
[1] => red

[1] => 4
[2] => php

)
Array
(
[2] => Array
(
[0] => green
[1] => red
)
[1] => 4
[0] => php)

14) Miscellaneous Function



1) Define()
(PHP 4, PHP 5)
define — Defines a named constant
Description
bool define ( string $name , mixed $value [, bool
$case_insensitive= false ] )
Defines a named constant at runtime
...

value

The value of the constant; only scalar and null values are
allowed
...
It is possible to define resource constants, however it
is not recommended and may cause unpredictable behavior
...

The default behavior is case-sensitive; i
...
CONSTANT and
Constant represent different values
...

Examples
Example #1 Defining Constants
define("CONSTANT", "Hello world
...
"
echo Constant; // outputs "Constant" and issues a notice
...
", true);
echo GREETING; // outputs "Hello you
...
"
?>

2) Constant()
(PHP 4 >= 4
...
4, PHP 5)
constant — Returns the value of a constant
Description
mixed constant ( string $name )
Return the value of the constant indicated by name
...
I
...
it is stored in a
variable or returned by a function
...

Parameters
name

The constant name
...

Examples
Example #1 constant() example
define("MAXSIZE", 100);
echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

interface bar {
const test = 'foobar!';
}
class foo {
const test = 'foobar!';
}
$const = 'test';
var_dump(constant('bar::'
...
$const)); // string(7) "foobar!"
?>

3) include()
The include() statement includes and evaluates the specified
file
...
The two
constructs are identical in every way except how they handle
failure
...
In other words, use require() if you want a
missing file to halt processing of the page
...
Be sure to
have an appropriate include_path setting as well
...
3
...
Since this version,
it does
...
E
...
if your include_path is
libraries, current working directory is /www/, you included
include/a
...
php" in that file, b
...
If
filename begins with
...
/, it is looked for only in the
current working directory or parent of the current working
directory, respectively
...
Any
variables available at that line in the calling file will be
available within the called file, from that point forward
...

Eg
...
php
$color = 'green';
$fruit = 'apple';
?>
test
...
php';
echo "A $color $fruit"; // A green apple
?>

4) require()
require() is identical to include() except upon failure it will
produce a fatal E_ERROR level error
...

Eg
...
php");
if (class_exists("motherclass"))
echo "It exists";

?>

5) Header()
(PHP 4, PHP 5)
header — Send a raw HTTP header
Description
void header ( string $string [, bool $replace= true [, int
$http_response_code ]] )
header() is used to send a raw HTTP header
...
1 specification for more information on HTTP headers
...
It is a very common error to read code with
include(), or require(), functions, or another file access
function, and have spaces or empty lines that are output
before header() is called
...


/* This will give an error
...
example
...

There are two special-case header calls
...

For example, if you have configured Apache to use a PHP
script to handle requests for missing files (using the
ErrorDocument directive), you may want to make sure that
your script generates the proper status code
...
0 404 Not Found");
?>

The second special case is the "Location:" header
...

header("Location: http://www
...
com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect
...


15) File system function




fopen — Opens file or URL
syntax:
resource fopen ( string $filename , string $mode [, bool
$use_include_path [, resource $context ]] )


fopen() binds a named resource, specified by filename , to a
stream
...
", it is assumed to be a
URL and PHP will search for a protocol handler (also known as
a wrapper) for that scheme
...

If PHP has decided that filename specifies a local file, then it will
try to open a stream on that file
...
If you have enabled safe mode, or
open_basedir further restrictions may apply
...
If it is
switched off, PHP will emit a warning and the fopen call will
fail
...
Some protocols (also referred
to as wrappers) support context and/or php
...
Refer
to the specific page for the protocol in use for a list of options
which can be set
...
g
...
ini value user_agent used by the
http wrapper)
...

$handle = fopen("c:\\data\\info
...
It may be any of the following:
A list of possible modes for fopen() using mode
mode

Description

'r'

Open for reading only; place the file pointer at the
beginning of the file
...


'w'

Open for writing only; place the file pointer at the
beginning of the file and truncate the file to zero length
...


'w+'

Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length
...


'a'

Open for writing only; place the file pointer at the end of
the file
...


'a+'

Open for reading and writing; place the file pointer at the
end of the file
...


'x'

Create and open for writing only; place the file pointer at
the beginning of the file
...
If the file does not exist, attempt
to
create
it
...


'x+'

Create and open for reading and writing; place the file
pointer at the beginning of the file
...
If the file does not
exist, attempt to create it
...

Return Values
Returns a file pointer resource on success, or FALSE on error
...
txt", "r");
fopen("/home/rasmus/file
...
example
...
com/somefile
...
Reading stops as soon as one of the following
conditions is met:
length bytes have been read
EOF (end of file) is reached
a packet becomes available (for network streams)
8192 bytes have been read (after opening userspace stream)
Parameters
handle

A file system pointer resource that is typically created using
fopen()
...

Return Values
Returns the read string or FALSE in case of error
...
txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>



fwrite — Binary-safe file write



syntax:
int fwrite ( resource $handle , string $string [, int $length ] )
fwrite() writes the contents of string to the file stream pointed
to by handle
...

string

The string that is to be written
...

Note that if the length argument is given, then the
magic_quotes_runtime configuration option will be ignored
and no slashes will be stripped from string
...

$fp = fopen('data
...
txt' is now 123 and not 23!
?>

Example
$filename = 'test
...

if (is_writable($filename)) {
// In our example we're opening $filename in append mode
...

if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file
...

Parameters
handle

The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen()
...

Example
$handle = fopen('somefile
...

Parameters
filename

Path to the file or directory
...

This function will return FALSE for symlinks pointing to nonexisting files
...
txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>



is_readable
readable



Tells

whether

the

filename

is

syntax:
bool is_readable ( string $filename )


Tells whether the filename is readable
...

Return Values:
Returns TRUE if the file or directory specified by filename exists
and is readable, FALSE otherwise
...
txt';
if (is_readable($filename)) {
echo 'The file is readable';
} else {
echo 'The file is not readable';
}
?>



is_writable — Tells whether the filename is writable
syntax:
bool is_writable ( string $filename )




Returns TRUE if the filename exists and is writable
...

Keep in mind that PHP may be accessing the file as the user id
that the web server runs as (often 'nobody')
...

Parameters
filename

The filename being checked
...

Example
$filename = 'test
...

Parameters
handle

The file pointer must be valid, and must point to a file
successfully opened by fopen() or fsockopen() (and not yet
closed by fclose())
...
If no length is specified, it will keep
reading from the stream until it reaches the end of the line
...
3
...
If the majority of the lines in the file are all larger
than 8KB, it is more resource efficient for your script to specify
the maximum line length
...

If an error occurs, returns FALSE
...
txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>



fgetc — Gets character from file pointer
syntax:
string fgetc ( resource $handle )



Gets a character from the given file pointer
...

Return Values:
Returns a string containing a single character read from the
file pointed to by handle
...


Example
$fp = fopen('somefile
...
txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>



file — Reads entire file into an array
syntax:
array file ( string $filename [, int $flags [, resource $context ]] )




Reads an entire file into an array
...

Parameters
filename

Path to the file
...

Return Values:
Returns the file in an array
...

Upon failure, file() returns FALSE
...
In this example we'll go through HTTP to get
// the HTML source of a URL
...
example
...

foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : "
...
"
>\n";
}
// Another example, let's get a web page into a string
...

$html = implode('', file('http://www
...
com/'));
// Using the optional flags parameter since PHP 5
$trimmed = file('somefile
...
On failure, file_get_contents() will return FALSE
...
It will use memory mapping techniques if
supported by your OS to enhance performance
...

flags

Return Values
The function returns the read data or FALSE on failure
...




If filename does not exist, the file is created
...

Parameters
filename

Path to the file where to write the data
...
Can be either a string, an array or a stream
resource (explained above)
...
This is similar with
using stream_copy_to_stream()
...
This is equivalent to file_put_contents($filename,
implode('', $array))
...

Parameters
handle

The file pointer must be valid, and must point to a file
successfully opened by fopen() or popen()
...

Return Values



Returns the position of the file pointer referenced by handle as
an integer; i
...
, its offset into the file stream
...


Example
// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);
// where are we ?
echo ftell($fp); // 11
fclose($fp);
?>



fseek — Seeks on a file pointer
syntax:
int fseek ( resource $handle , int $offset [, int $whence ] )


Sets the file position indicator for the file referenced by handle
...

Parameters
handle

A file system pointer resource that is typically created using
fopen()
...

To move to a position before the end-of-file, you need to pass
a negative value in offset
...

SEEK_CUR - Set position to current location plus offset
SEEK_END - Set position to end-of-file plus offset
...


If whence is not specified, it is assumed to be SEEK_SET
...
Note that
seeking past EOF is not considered an error
...
txt', 'r');
// read some data
$data = fgets($fp, 4096);
// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);
?>



rewind — Rewind the position of a file pointer
syntax:
bool rewind ( resource $handle )



Sets the file position indicator for handle to the beginning of the
file stream
...

Parameters
handle

The file pointer must be valid, and must point to a file
successfully opened by fopen()
...

Example
$handle = fopen('output
...
');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);
echo fread($handle, filesize('output
...




copy — Copies file
syntax:
bool copy ( string $source , string $dest [, resource $context ] )



Makes a copy of the file source to dest
...

Parameters
source

Path to the source file
...
If dest is a URL, the copy operation may
fail if the wrapper does not support overwriting of existing
files
...

context

A
valid
context
stream_context_create()
...

Example
$file = 'example
...
txt
...
\n";
}
?>



unlink — Deletes a file
Syntax:
bool unlink ( string $filename [, resource $context ] )


Deletes filename
...

Parameters
filename

Path to the file
...
0
...
For a
description of contexts, refer to Stream Functions
...

Example
$fh = fopen('test
...
html');
unlink('testdir');
?>



rename — Renames a file or directory
syntax:
bool rename ( string $oldname , string $newname [, resource
$context ] )


Attempts to rename oldname to newname
...
The wrapper used in oldname must match the
wrapper used in newname
...

context

Context support was added with PHP 5
...
0
...

Return Values
Returns TRUE on success or FALSE on failure
...
txt", "/home/user/login/docs/my_file
...
PHP GD Library:-------------The GD library is used for dynamic image creation
...
This allows us to do things such as create
charts on the fly, created an an anti-robot security image, create
thumbnail images, or even build images from other images
...
If you don't have it, you can
download it for free
...
You should already have some PHP knowledge before you
start
...
About
...

With this code we are creating a PNG image
...
If we were creating a jpg
or gif image, this would change accordingly
...

Next we have the image handle
...
Our rectangle is 130 pixels wide, and 50 pixels high
...

Next we set our background color
...
The first is our

handle, and the next three determine the color
...
It gives you the integers for basic web colors
if you are not familiar with choosing colors in this format
...

4
...
We have chosen black
...

Now we enter the text we want to appear in our graphic
using ImageString ()
...
Then the
font (1-5), starting X ordinate, starting Y ordinate, the text itself,
and finally it's color
...

Finally ImagePng () actually creates the PNG image
...
ttf", "Quel");
ImagePng ($handle);
?>
Although most of our code has stayed the same you will notice we
are now using ImageTTFText () instead of ImageString ()
...

The first parameter is our handle, then font size, rotation, starting
X, starting Y, text color, font, and finally our text
...
For our
example I have placed the font Quel in a folder called Fonts
...

If your text isn't showing, you may have the path to your font
wrong
...


Drawing Lines
$handle = ImageCreate (130, 50) or die ("Cannot Create image");
$bg_color = ImageColorAllocate ($handle, 255, 0, 0);
$txt_color = ImageColorAllocate ($handle, 255, 255, 255);
$line_color = ImageColorAllocate ($handle, 0, 0, 0);
ImageLine($handle, 65, 0, 130, 50, $line_color);
ImageString ($handle, 5, 5, 18, "PHP
...
com", $txt_color);
ImagePng ($handle);
?>
In this code, we use ImageLine () to to draw a line
...

To make a cool volcano like we have in our example, we simply
put this into a loop, keeping our starting coordinates the same, but
moving along the x axis with our finishing coordinates
...
About
...
About
...
Like we did with our line, we can also put our ellipse
into a loop to create a spiral effect
...
About
...

Arcs & Pies
header('Content-type: image/png');
$handle = imagecreate(100, 100);
$background = imagecolorallocate($handle, 255, 255, 255);
$red = imagecolorallocate($handle, 255, 0, 0);
$green = imagecolorallocate($handle, 0, 255, 0);
$blue = imagecolorallocate($handle, 0, 0, 255);
imagefilledarc($handle, 50, 50, 100, 50, 0, 90, $red,
IMG_ARC_PIE);
imagefilledarc($handle, 50, 50, 100, 50, 90, 225 , $blue,
IMG_ARC_PIE);
imagefilledarc($handle, 50, 50, 100, 50, 225, 360 , $green,
IMG_ARC_PIE);
imagepng($handle);
?>

Using imagefilledarc we can create a pie, or a slice
...
The start and end points are in degrees, starting
from the 3 o'clock position
...

IMG_ARC_PIE- Filled arch
2
...

IMG_ARC_NOFILL- when added as a parameter, makes
it unfilled
4
...
You will use
this with nofill to make an unfilled pie
...
We just need to add this code in
under the colors and before the first filled arc
...
About
...

Above, we are creating a GIF using the ImageGif () function
...
You can also use ImageJpeg
() to create a JPG, as long as the headers change to reflect it
appropriately
...

For example:
preceding expression", * means "Match zero or more of the
preceding expression", and ? means "Match zero or one of the
preceding expression"
...

With a single integer, {n} means "match exactly n occurrences of
the preceding expression", with one integer and a comma, {n,}
means "match n or more occurrences of the preceding
expression", and with two comma-separated integers {n,m}
means "match the previous character if it occurs at least n times,
but no more than m times"
...
\-]
^[a-zA-Z09_]{1,}$
([wx])([yz])
[^A-Za-z0-9]
([A-Z]{3}|[09]{4})

Will match
...
Usually, the slash (/) character is used
...

The PCRE functions can be divided in several classes: matching,
replacing, splitting and filtering
...
preg_match() takes two basic and three optional
parameters
...
Let's search the string "Hello World!" for the letters
"ll":
if (preg_match("/ell/", "Hello World!", $matches)) {
echo "Match was found
";
echo $matches[0];
}
?>
The letters "ll" exist in "Hello", so preg_match() returns 1 and the
first element of the $matches variable is filled with the string that
matched the pattern
...
*/", "The History of Halloween", $matches)) {
echo "Match was found
";
echo $matches[0];
}
?>

Now let's consider more complicated example
...
The example below
checks if the password is "strong", i
...
the password must be at
least 8 characters and must contain at least one lower case letter,
one upper case letter and one digit:
$password = "Fyfjk34sdfjfsjq7";
if (preg_match("/^
...
*\d)(?=
...
*[A-Z])
...
";
} else {
echo "Your password is weak
...
The "
...
As mentioned above, the
...
Between are groupings in parentheses
...
This
construct doesn't capture the text
...

The first grouping is (?=
...
This checks if there are at least 8
characters in the string
...
*[0-9]) means "any
alphanumeric character can happen zero or more times, then any
digit can happen"
...
But since the string isn't captured, that one digit can
appear anywhere in the string
...
*[a-z]) and
(?=
...

Finally, we will consider regular expression that validates an
email address:

$email = firstname
...
bbb
...
][A-z0-9_]+)*[@][A-z09_]+([
...
][A-z]{2,4}$/";
if (preg_match($regexp, $email)) {
echo "Email address is valid
...
";
}
?>
This regular expression checks for the number at the beginning
and also checks for multiple periods in the user name and domain
name in the email address
...

For the speed reasons, the preg_match() function matches only
the first pattern it finds in a string
...
An alternative function,
preg_match_all(), matches a pattern against a string as many
times as the pattern allows, and returns the number of times it
matched
...
The preg_replace() function
looks for substrings that match a pattern and then replaces them
with new text
...
These parameters are, in order, a regular
expression, the text with which to replace a found pattern, the
string to modify, and the last optional argument which specifies
how many matches will be replaced
...
In the
following example we search for the copyright phrase and replace
the year with the current
...
Back references make it possible for you to use part of a
matched pattern in the replacement string
...
You can refer to the text
matched by subpattern with a dollar sign ($) and the number of
the subpattern
...

In the following example we will change the date format from
"yyyy-mm-dd" to "mm/dd/yyy":
echo preg_replace("/(\d+)-(\d+)-(\d+)/", "$2/$3/$1", "2007-0125");
?>
We also can pass an array of strings as subject to make the
substitution on all of them
...
Have a look
at the example:
$search = array ( "/(\w{6}\s\(w{2})\s(\w+)/e",
"/(\d{4})-(\d{2})-(\d{2})\s(\d{2}:\d{2}:\d{2})/");
$replace = array ('"$1 "
...
Since we have
appended an "e" to the end of the regular expression, PHP will
execute the replacement it makes
...

Array Processing
PHP's preg_split() function enables you to break a string apart
basing on something more complicated than a literal sequence of
characters
...
The basic idea is the same as preg_match_all() except
that, instead of returning matched pieces of the subject string, it
returns an array of pieces that didn't match the specified pattern
...
This
function traverses the input array, testing all elements against the
supplied pattern
...
The following
example searches through an array and all the names starting with
letters A-J:
$names = array('Andrew','John','Peter','Nastin','Bill');
$output = preg_grep('/^[a-m]/i', $names);
print_r( $output );
?>

Now let's see a detailed pattern syntax reference:
Regular expression
(pattern)

Match (subject)

Not match (subject)

Comment

world

Hello world

Hello Jim

Match if the pattern is
present anywhere in the
subject

Hello world

Match if the pattern is
present at the beginning
of the subject

^world

world class

world$

Hello world

world class

Match if the pattern is
present at the end of the
subject

world/i

This WoRLd

Hello Jim

Makes a search in case
insensitive mode

^world$

world

Hello world

The string contains only
the "world"

world*

worl, world, worlddd

wor

There is 0 or more "d"
after "worl"

world+

world, worlddd

worl

There is at least 1 "d"
after "worl"

world?

worl, world, worly

wor, wory

There is 0 or 1 "d" after
"worl"

world{1}

world

worly

There is 1 "d" after
"worl"

world{1,}

world, worlddd

worly

There is 1 ore more "d"
after "worl"

world{2,3}

worldd, worlddd

world

There are 2 or 3 "d"
after "worl"

wo(rld)*

wo, world, worldold

wa

There is 0 or more "rld"
after "wo"

earth|world

earth, world

sun

The string contains the
"earth" or the "world"

w
...


^
...
Cookies:--------------

A cookie is often used to identify a user
...
A cookie is a small file
that the server embeds on the user's computer
...
With PHP, you can both create and retrieve cookie values
...

Note: The setcookie() function must appear BEFORE the
tag
...
We also specify that the
cookie should expire after one hour:
setcookie("user", "Alex Porter", time()+3600);
?>


...

Example 2

You can also set the expiration time of the cookie in another way
...

$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>


...

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value
...
$_COOKIE["user"]
...

Delete example:
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support
cookies, you will have to use other methods to pass information
from one page to another in your application
...

The form below passes the user input to "welcome
...
php" method="post">
Name:
Age:




Retrieve the values in the "welcome
...


You are years old
...
In this tutorial, Timothy gives you
an overview of cookies to help you understand how they work
...

The information is constantly passed in HTTP headers between
the browser and web server; the browser sends the current cookie
as part of its request to the server and the server sends updates to
the data back to the user as part of its response
...
The information can really be
anything
...

In addition to the information it stores, each cookie has a set of
attributes: an expiration date, a valid domain, a valid domain path
and an optional security flag
...


 4
...
Session variables hold
information about one single user, and are available to all pages in
one application
...
This is much like a Session
...
It knows when you start the
application and when you end
...

A PHP session solves this problem by allowing you to store user
information on the server for later use (i
...
username, shopping
items, etc)
...
If you need a
permanent storage you may want to store the data in a database
...
The UID is either stored in a
cookie or is propagated in the URL
...

Note: The session_start() function must appear BEFORE the
tag:





The code above will register the user's session with the server,
allow you to start saving user information, and assign a UID for
that user's session
...
$_SESSION['views'];
?>


Output:
Pageviews=1

In the example below, we create a simple page-views counter
...
If "views" has been set, we can increment our counter
...
$_SESSION['views'];
?>

Destroying a Session

If you wish to delete some session data, you can use the unset() or
the session_destroy() function
...


 5
...
This will
include things like, the browser the visitor is using, the IP
address, and which web page the visitor came from
...

$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
print "Referrer = "
...
"
";
print "Browser = "
...
"
";
print "IP Adress = "
...
)
So to get at the values in Server Variables, the syntax is this:
$_SERVER['Server_Variable']
You start with a dollar sign, then an underscore character ( $_ )
...
In between square brackets,
you type the name of the server variable you want to access
...

Because you are returning a value, you need to put all that on
the right hand side of an equals sign
...

The server variables are held in an array (associative), so you
can use a foreach loop to get a list of all available ones
...
$key_value
...

Server Variables are those variables which are inside the super
global array named $_SERVER available in PHP
...
I’m going to post here some
of the very useful server variables available in PHP
development
...
If you need to type
http://www
...
com/product
...
php?id=5″
...
This variable usually returns the path like
“/usr/yoursite/www” in Linux and “D:/xamps/xampp/htdocs” in
windows
...
This variable usually returns the path
like “example
...
com” in
browser’s address-bar and return “www
...
com” when
you see http://www
...
com in the address-bar
...
com” is not same as for the
“http://www
...
com”
...
We can use
strpos($_SERVER["HTTP_USER_AGENT"],”MSIE”) to
detect Microsoft Internet explorer or you can use

strpos($_SERVER["HTTP_USER_AGENT"],”Firefox”) to
detect firefox browser in PHP
...
Let’s suppose that you’re accessing
the URL http://www
...
com/product
...
php” in your script
...

Query strings are those string which is available after “?” sign
...
example
...
php?id=5&page=product” then
it returns “id=5&page=product” in your script
...
But you can’t
relie on $_SERVER['REMOTE_ADDR'] to get the real IP
address of client’s machine
...

8 ) $_SERVER['SCRIPT_FILENAME'] - Returns the
absolute path of the file which is currently executing
...
com/www/product
...
php” in
windows
...
Database connectivity with MySQL:----------MySQL is the most popular open source database server
...
A database defines a structure for
storing information
...
Just like HTML tables,
database tables contain rows, columns, and cells
...
A
company may have a database with the following tables:
"Employees", "Products", "Customers" and "Orders"
...
Each table
has a name (e
...
"Customers" or "Orders")
...

Below is an example of a table called "Persons":
LastName

FirstName

Hansen

Ola

Svendson

Tove

Pettersen

Kari

Address
Timoteivn
10
Borgvn
23
Storgt 20

City
Sandnes
Sandnes
Stavanger

The table above contains three records (one for each person)
and four columns (LastName, FirstName, Address, and City)
...

With MySQL, we can query a database for specific information
and have a recordset returned
...
Perhaps it is
because of this reputation that many people believe that
MySQL can only handle small to medium-sized systems
...

Connecting to a MySQL Database
Before you can access and work with data in a database, you
must create a connection to the database
...

Syntax:
mysql_connect(servername,username,password);
Parameter
servername
username

password

Description
Optional
...

Default value is "localhost:3306"
Optional
...

Default value is the name of the user that owns
the server process
Optional
...

Default is ""

Note: There are more available parameters, but the ones
listed above are the most important
...

Example
In the following example we store the connection in a variable
($con) for later use in the script
...
mysql_error());
}
// some code
?>



mysql_select_db — Select a MySQL database
syntax:
bool mysql_select_db ( string $database_name [, resource
$link_identifier ] )
Sets the current active database on the server that's
associated with the specified link identifier
...

Parameters
database_name

The name of the database that is to be selected
...
If the link identifier is not specified,
the last link opened by mysql_connect() is assumed
...
If by chance
no connection is found or established, an E_WARNING level
error is generated
...


Examples:
Example #1 mysql_select_db() example
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : '
...
mysql_error());
}
?>

 mysql_close()-Closing a Connection
The connection will be closed as soon as the script ends
...

$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: '
...

Create a Database
The CREATE DATABASE statement is used to create a
database in MySQL
...
This function is used to send a query
or command to a MySQL connection
...
mysql_error());
}
if
(mysql_query("CREATE
DATABASE
my_db",$con))
{
echo "Database created";
}
else
{
echo
"Error
creating
database:
"

...

Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,

...


to

the

Example
The following example shows how you can create a table
named "Person", with three columns
...
mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: "
...
The database is selected with the mysql_select_db()
function
...
g
...

 MySQL Data Types
Below is the different MySQL data types that can be used:

Numeric
Data
Types
int(size)
smallint(size)
tinyint(size)
mediumint(size)
bigint(size)
decimal(size,d)
double(size,d)
float(size,d)

Description

Textual
Types
char(size)

Description

Data

varchar(size)

Tinytext
text
blob
mediumtext
mediumblob
longtext
longblob

Hold integers only
...

The
maximum number of digits can be
specified in the size parameter
...

The fixed size is specified in parenthesis
Holds a variable length string (can contain
letters, numbers, and special characters)
...
Data Types

Description
Holds date and/or time

Description

enum(value1,value2,ect)

set

ENUM is short for ENUMERATED list
...
If a
value is inserted that is not in the list,
a blank value will be inserted
SET is similar to ENUM
...







A primary key is used to uniquely identify the rows in a table
...

Furthermore, the primary key field cannot be null because the
database engine requires a value to locate the record
...
There is no exception
to this rule! You must index the primary key field so the
database engine can quickly locate rows based on the key's
value
...
The primary key field is often an ID number, and is
often
used
with
the
AUTO_INCREMENT
setting
...
To ensure that the
primary key field cannot be null, we must add the NOT NULL
setting to the field
...

Insert Data Into a Database Table
The INSERT INTO statement is used to add new records to a
database table
...
)
You can also specify the columns where you want to insert the
data:
INSERT INTO table_name (column1, column2,
...
)
Note: SQL statements are not case sensitive
...

To get PHP to execute the statements above we must use the
mysql_query() function
...

Example
In the previous chapter we created a table named "Person",
with three columns; "Firstname", "Lastname" and "Age"
...
The following example
adds two new records to the "Person" table:
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: '
...

Here is the HTML form:


...
php" file connects to a database, and retrieves the
values from the form with the PHP $_POST variables
...

Below is the code in the "insert
...
mysql_error());
}
mysql_select_db("my_db", $con);

$sql="INSERT INTO person (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: '
...

Select Data From a Database Table
The SELECT statement is used to select data from a database
...
SELECT is the
same as select
...
This function is used to send a query
or command to a MySQL connection
...
mysql_error());
}
mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName']
...
Next, we use
the mysql_fetch_array() function to return the first row from
the recordset as an array
...

The while loop loops through all the records in the recordset
...

The output of the code above will be:
Peter Griffin
Glenn Quagmire
Display the Result in an HTML Table
The following example selects the same data as the example
above, but will display the data in an HTML table:
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: '
...
$row['FirstName']
...
$row['LastName']
...

The WHERE clause
To select only data that matches a specific criteria, add a
WHERE clause to the SELECT statement
...
WHERE is the
same as where
...
This function is used to send a query
or command to a MySQL connection
...
mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName']
...


The ORDER BY Keyword
The ORDER BY keyword is used to sort the data in a recordset
...
ORDER BY is the
same as order by
...
mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person ORDER BY
age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " "
...
$row['Age'];
echo "
";
}
mysql_close($con);
?>
The output of the code above will be:
Glenn Quagmire 33
Peter Griffin 35

Sort Ascending or Descending
If you use the ORDER BY keyword, the sort-order of the
recordset is ascending by default (1 before 9 and "a" before
"p")
...
When
ordering by more than one column, the second column is only
used if the values in the first column are identical:
SELECT column_name(s)
FROM table_name
ORDER BY column_name1, column_name2
PHP MySQL Update
The UPDATE statement is used to modify data in a database
table
...

Syntax:
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
Note: SQL statements are not case sensitive
...


To get PHP to execute the statement above we must use the
mysql_query() function
...

Example
Earlier in the tutorial we created a table named "Person"
...
mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Person SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
mysql_close($con);
?>
After the update, the "Person" table will look like this:
FirstNa
me
Peter
Glenn

LastNa
me
Griffin
Quagmir
e

Ag
e
36
33

PHP MySQL Delete From
The DELETE FROM statement is used delete rows from a
database table
...

Syntax
DELETE FROM table_name
WHERE column_name = some_value
Note: SQL statements are not case sensitive
...

To get PHP to execute the statement above we must use the
mysql_query() function
...

Example
Earlier in the tutorial we created a table named "Person"
...
mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE
LastName='Griffin'");
mysql_close($con);
?>

FROM

Person

WHERE

After the deletion, the table will look like this:
FirstNa
me
Glenn

LastNa
me
Quagmir
e

Ag
e
33

Fetching data set



mysql_fetch_row — Get a result row as an enumerated
array
syntax:
array mysql_fetch_row ( resource $result )
Returns a numerical array that corresponds to the fetched row
and moves the internal data pointer ahead
...
This result comes
from a call to mysql_query()
...

mysql_fetch_row() fetches one row of data from the result
associated with the specified result identifier
...
Each result column is stored in an array
offset, starting at offset 0
...
mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>



mysql_fetch_object — Fetch a result row as an object

syntax:
object

mysql_fetch_object (
$class_name [, array $params ]] )

resource

$result

[,

string

Returns an object with properties that correspond to the
fetched row and moves the internal data pointer ahead
...
This result comes
from a call to mysql_query()
...
If not specified, a stdClass object is returned
...

Return Values
Returns an object with string properties that correspond to the
fetched row, or FALSE if there are no more rows
...
The row is
returned as an array
...

Examples
Example 1 mysql_fetch_object() example
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>



mysql_fetch_array — Fetch a result row as an associative
array, a numeric array, or both
syntax:

array mysql_fetch_array ( resource $result [, int $result_type ]
)
Returns an array that corresponds to the fetched row and
moves the internal data pointer ahead
...
This result comes
from a call to mysql_query()
...
It's a constant and can
take the following values: MYSQL_ASSOC, MYSQL_NUM, and the
default value of MYSQL_BOTH
...
The type of returned
array depends on how result_type is defined
...
Using MYSQL_ASSOC, you only
get associative indices (as mysql_fetch_assoc() works), using
MYSQL_NUM,
you
only
get
number
indices
(as
mysql_fetch_row() works)
...
To access the
other column(s) of the same name, you must use the numeric
index of the column or make an alias for the column
...

Examples
Example #1 Query with aliased duplicate field names
SELECT table1
...
field AS bar FROM table1,
table2
Example #2 mysql_fetch_array() with MYSQL_NUM
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: "
...
PHP with OOPS
Class:Definition of a Class
A class is user defined data type that contains attributes or data
members; and methods which work on the data members
...
This
tutorial focuses only on learning how to create a Class in PHP5)
To create a class, you need to use the keyword class followed by the
name of the class
...
The body of the class is placed between two curly brackets
within which you declare class data members/variables and class
methods
...
$this->last_name;
}

Constructor:Definition of a ConstructorA constructor is a special function of a class that is automatically
executed whenever an object of a class gets instantiated
...
A constructor is a
special function - this means that a constructor is a function; but its
special
...

Why do we need a Constructor?
It is needed as it provides an opportunity for doing necessary setup
operations like initializing class variables, opening database connections
or socket connections, etc
...

PHP5 Constructor
In PHP5 a constructor is defined by implementing the __construct()
method
...
In PHP4, the
name of the constructor was the same name as that of the class
...

PHP5 to be backward complaint also supports the PHP4 rule
...
If __construct()
is not defined it then searches for a method with the same that of the
class
...

Let’s look at how to define a PHP5 Constructor
class Customer {

public function __construct() {
//code
}
}
Let’s look at a real example:
class Customer {
private $first_name;
private $last_name;
private $outstanding_amount;
public function __construct() {
$first_name = "";
$last_name = "";
$outstanding_amount = 0;
}
public function setData($first_name, $last_name,
$outstanding_amount) {
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->outstanding_amount = $outstanding_amount;
}
public function printData() {
echo "Name : "
...
$this->last_name
...
$this->outstanding_amount

...
This means that an object is
created from the definition of the class and is loaded in memory
...
If God wants to send a

human to earth, what is easy for Him to do? Create and define properties
and attributes of each human separately or create a one time template
and generate objects out if it
...

Creating Objects in PHP5 Class
To create an object of a PHP5 class we use the keyword new
...
$this->last_name;
}
}
$c1 = new Customer();
$c2 = new Customer();
Therefore, an object is a living instance of a class
...


Inheritance:One of the main feature of Object Oriented Programing which is called
Inheritance
...
The derived class shares/inherit the
functionality of the base class
...

While performing Inheritance operation Access Specifiers specify the
level of access that the outside world (other objects and functions) have
on the data members / member functions of the class
...
To access private data of parent class
from derived class you will have to call public/protected method of the
parent class which will access the private variable and return the data to
the derived class
...
i
...
You
can inherit only one class
...

Explanation: Parent is the Keyword in PHP5 and it cannot be used in
PHP5 for declaring classname
...
Now the children class can access the $firstname and
$lastname attributes
...
It can be used to perform some fairly
complex operations, in fact
...


Introduction
Anyone who has been using PHP object-oriented programming for a
while knows that object serialization can be a useful approach, which
can be utilized for different purposes
...

Certainly one of the best things about serializing objects is its extreme
ease to perform, trust me
...

The truth is that when it comes to serializing objects, PHP makes the
whole process a no-brainer task
...

As you can see, serializing objects in PHP is a very useful approach,
which deserves at least a closer analysis
...

What should you expect from this series? By the end of it, you should be
equipped with a decent knowledge of how to serialize/unserialize objects
without losing their methods and properties during the transition, as well
as constructing persisting and session objects, and much more
...

In order to illustrate how an object, that is converted to a byte-stream
representation of its methods and properties, can be serialized, I’ll set up
a concrete example that will show the complete sequence for
serializing/unserializing the object in question
...
Thus, here is a
sample PHP class named “DataSaver,” which is simply tasked with
saving an input string to a given text file
...
'/data
...
'/data
...
Now, pay
attention to the following snippet, where an instance of the “DataSaver”
class is serialized, and in turn restored to its original state:
// instantiate 'datasaver' object
$dataSaver=&new DataSaver('This string will be saved to file');
// save data to file
$dataSaver->save();
// display sample data
echo $dataSaver->fetch()
...

Notice how after instantiating a "DataSaver" object, and calling its
“save()” and fetch()” methods, this object is serialized and next
unserialized through the corresponding “serialize()/unserialize()”
functions
...
The
following lines clearly illustrate this concept:
// serialize object
$dataObj=serialize($dataSaver);
$dataObj=unserialize($dataObj);
// call object methods after unserializing object
echo $dataObj->fetch();
The output of the above snippet is as follows:
This string will be saved to file
Certainly, the above example demonstrates the ease, offered by PHP, of
serializing an object inside an application, as well as reversing the
process and using the object’s methods and properties accordingly
...

After showing the first example of how to serialize/unserialize an object,
I hope you understand how the whole process works, as well as the
possible implementations of this technique inside an application
...
Sounds a little bit confusing? It isn't
...
'/data
...
'/data
...
'/data
...
In this case, the
“saveSerialized()” method takes up the object itself, then serializes it and
finally saves it to the specified text file
...
But in fact, I’m getting ahead of myself
...

As you learned in the previous section, creating objects that serialize
themselves is a fairly comprehensive process, since all you have to do is
add to the corresponding class a method capable of saving the serialized
object to a specified file, or in many cases, to a database table
...
So,
what if I tell you that it’s possible to create objects that not only serialize
and save to a file themselves, but also are capable of performing a selfrestoring process?

Actually, this kind of object is called a “self-saving” object, and the class
defined below demonstrates how to create it
...
txt'){
$this->objectFile=$objectFile;
$this->save();
}
// save serialized object to file
function save(){
if(!$fp=fopen($this->objectFile,'w')){
trigger_error('Error opening object
file',E_USER_ERROR);
}
if(!fwrite($fp,serialize($this))){
trigger_error('Error writing data to object
file',E_USER_ERROR);
}
fclose($fp);
}
// fetch object from file
function fetch(){
if(!$obj=unserialize(file_get_contents($this>objectFile))){
trigger_error('Error fetching object from
file',E_USER_ERROR);
}
return $obj;
}
}
As you can see, the sample “ObjectSaver” class that I coded above
shows a typical example of how to create an object that is capable of
serializing and deserializing itself
...


To complement the concept of creating self-saving objects, the above
class uses a simple text file both for storing the serialized object and
restoring it back to its original state
...

Now that you learned how to create self-saving objects based on the
“ObjectSaver” class that I defined previously, take a look at the
following example, which demonstrates how to use these objects:
// instantiate 'objectsaver' object
$objSaver=&new ObjectSaver();
// fetch unserialized object
$newObj=$objSaver->fetch();
As illustrated above, after a new “ObjectSaver” object has been
instantiated, its “fetch()” method is called explicitly, in order to
unserialize the object and store it in the “$newObj” variable
...
PHP with XML

 XML Introduction:The built-in Expat parser makes it possible to process XML documents
in PHP
...

What is XML?
XML is a markup language
...
XML
was released in the late 90's and has since received a great amount of
hype
...







XML
XML
XML
XML
XML

stands for EXtensible Markup Language
is a markup language much like HTML
was designed to carry data, not to display data
tags are not predefined
...

XML and HTML were designed with different goals:
XML was designed to transport and store data, with focus on
what data is
...



HTML is about displaying information, while XML is about carrying
information
...
XML
was created to structure, store, and transport information
...
It has sender and receiver information,
it also has a heading and a message body
...
It is just pure information
wrapped in tags
...

XML is Just Plain Text
XML is nothing special
...
Software that can handle plain text
can also handle XML
...
The
functional meaning of the tags depends on the nature of the application
...
These tags are "invented" by the author of the XML document
...

The tags used in HTML (and the structure of HTML) are predefined
...

XML allows the author to define his own tags and his own document structure
...


It is important to understand that XML is not a replacement for HTML
...

My best description of XML is this:
XML is a software- and hardware-independent tool for carrying
information
...
February 1998
...

XML is Everywhere
We have been participating in XML development since its creation
...

XML is now as important for the Web as HTML was to the foundation of the
Web
...
It is the most common tool for data transmissions
between all sorts of applications, and is becoming more and more popular in
the area of storing and describing information
...
The rules are easy to
learn, and easy to use
...
All elements must have a closing
tag:

This is a paragraph


This is another paragraph



Note: You might have noticed from the previous example that the XML
declaration did not have a closing tag
...
The declaration is
not a part of the XML document itself, and it has no closing tag
...

XML tags are case sensitive
...

Opening and closing tags must be written with the same case:
This is incorrect
This is correct

Note: "Opening and closing tags" are often referred to as "Start and end tags"
...
It is exactly the same thing
...

XML Documents Must Have a Root Element
XML documents must contain one element that is the parent of all other
elements
...




...

In XML the attribute value must always be quoted
...
The first one is incorrect, the second is correct:

Tove
Jani


Tove
Jani


The error in the first document is that the date attribute in the note element is
not quoted
...

If you place a character like "<" inside an XML element, it will generate an
error because the parser interprets it as the start of a new element
...
The greater
than character is legal, but it is a good habit to replace it
...


White-space is Preserved in XML
HTML truncates multiple white-space characters to one single white-space:

HTML:

Hello

my name is Tove

Output:

Hello my name is Tove
...

XML Stores New Line as LF
In Windows applications, a new line is normally stored as a pair of characters:
carriage return (CR) and line feed (LF)
...
In Unix
applications, a new line is normally stored as a LF character
...


 Simple XML Functions:Table of Contents
SimpleXMLElement::addAttribute — Adds an attribute to the
SimpleXML element

SimpleXMLElement::addChild — Adds a child element to the
XML node

SimpleXMLElement::asXML — Return a well-formed XML
string based on SimpleXML element

SimpleXMLElement::attributes — Identifies an element's
attributes

SimpleXMLElement::children — Finds children of given node

SimpleXMLElement::__construct — Creates a new
SimpleXMLElement object

SimpleXMLElement::getDocNamespaces — Returns namespaces
declared in document

SimpleXMLElement::getName — Gets the name of the XML
element

SimpleXMLElement::getNamespaces — Returns namespaces
used in document

SimpleXMLElement::registerXPathNamespace — Creates a
prefix/ns context for the next XPath query

SimpleXMLElement::xpath — Runs XPath query on XML data

simplexml_import_dom — Get a SimpleXMLElement object
from a DOM node
...

Parameters
name
The name of the attribute to add
...

namespace
If specified, the namespace to which the attribute belongs
...

Examples
Example #1 Add attributes and children to a SimpleXML element
include 'example
...
');
$characters = $movie->addChild('characters');
$character = $characters>addChild('character');
$character->addChild('name', 'Mr
...

Parameters
name
The name of the child element to add
...

namespace

If specified, the namespace to which the child element belongs
...

Examples
Example #1 Add attributes and children to a SimpleXML element
include 'example
...
');
$characters = $movie->addChild('characters');
$character = $characters>addChild('character');
$character->addChild('name', 'Mr
...
0
...

Return Values
If the filename isn't specified, this function returns a string on success
and FALSE on error
...

Examples
Example #1 Get XML
$string = <<


text
stuff


code


XML;
$xml = new SimpleXMLElement($string);
echo $xml>asXML(); // ...

?>

4) SimpleXMLElement::__construct — Creates a new
SimpleXMLElement object

Description
SimpleXMLElement
__construct ( string $data [, int $options [, bool $data_is_url
[, string $ns [, bool $is_prefix ]]]] )
Creates a new SimpleXMLElement object
...

options
Optionally used to specify additional Libxml parameters
...
Use TRUE to specify that data
is a path or URL to an XML document instead of string data
...

Errors/Exceptions
Produces an E_WARNING error message for each error found in the
XML data and throws an exception if errors were detected
...
php';
$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

5) SimpleXMLElement::getName — Gets the name of the XML
element
Description
SimpleXMLElement
string getName ( void )
Gets the name of the XML element
...

Examples
Example #1 Get XML element names
$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->getName()
...
"\n";
}
?>

6) simplexml_load_file — Interprets an XML file into an object
Description
object simplexml_load_file ( string $filename [, string
$class_name= "SimpleXMLElement" [, int $options= 0 [, string
$ns [, bool $is_prefix= false ]]]] )
Convert the well-formed XML document in the given file to an object
...
g
...
com/?a='
...
Since PHP 5
...
0 you don't need to do this because
PHP will do it for you
...
That class should extend the
SimpleXMLElement class
...
1
...
6
...

ns
is_prefix
Return Values
Returns an object of class SimpleXMLElement with properties
containing the data held within the XML document
...

Examples
Example #1 Interpret an XML document
// The file test
...

if (file_exists('test
...
xml');
print_r($xml);
} else {
exit('Failed to open test
...
');

}
?>

 3
...


AJAX = Asynchronous JavaScript and XML
AJAX is not a new programming language, but a new technique for creating
better, faster, and more interactive web applications
...
With this object, a JavaScript can trade data with a
web server, without reloading the page
...

The AJAX technique makes Internet applications smaller, faster and more
user-friendly
...


AJAX is about better Internet-applications
Internet-applications have many benefits over desktop applications; they can
reach a larger audience, they are easier to install and support, and easier to
develop
...

With AJAX, Internet applications can be made richer and more user-friendly
...

AJAX is based on existing standards
...


PHP and AJAX
There is no such thing as an AJAX server
...
AJAX
uses HTTP requests to request small pieces of information from the server,
instead of whole pages
...


AJAX uses the XMLHttpRequest object
To get or send information from/to a database or a file on the server with
traditional JavaScript, you will have to make an HTML form, and a user will
have to click the "Submit" button to send/get the information, wait for the
server to respond, then a new page will load with the results
...

With AJAX, your JavaScript communicates directly with the server, through
the JavaScript XMLHttpRequest object
...
The user will stay on
the same page, and he or she will not notice that scripts request pages, or send
data to a server in the background
...


AJAX - Browser support
All new browsers use the built-in JavaScript XMLHttpRequest object to
create an XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject)
...
XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window
...
XMLHTTP");
}

The next chapter shows how to use the XMLHttpRequest object to
communicate with a PHP server
...
This is a JavaScript
object and is created as simply as shown in Listing 1
...
Create a new XMLHttpRequest object


I'll talk more about this object in the next article, but for now
realize that this is the object that handles all your server
communication
...
That's not the normal application flow and
it's where Ajax gets much of its magic
...
Then, the entire form is sent to the server, the server
passes on processing to a script (usually PHP or Java or maybe a
CGI process or something similar), and when the script is done, it
sends back a completely new page
...
Of course, while the script or program on the
server is processing and returning a new form, users have to wait
...
This is where low interactivity comes into play -users don't get instant feedback and they certainly don't feel like
they're working on a desktop application
...

When users fill out forms, that data is sent to some JavaScript code
and not directly to the server
...
While this is
happening, the form on the users screen doesn't flash, blink,
disappear, or stall
...
Even better, the request is sent
asynchronously, which means that your JavaScript code (and the

user) doesn't wait around on the server to respond
...

Then, the server sends data back to your JavaScript code (still
standing in for the Web form) which decides what to do with that
data
...
The JavaScript code could
even get the data, perform some calculations, and send another
request, all without user intervention! This is the power of
XMLHttpRequest
...

The result is a dynamic, responsive, highly-interactive experience
like a desktop application, but with all the power of the Internet
behind it
...
Since XMLHttpRequest is central to Ajax applications -and probably new to many of you -- I'll start there
...

Remember those pesky browser wars from a few years back and
how nothing worked the same across browsers? Well, believe it or
not, those wars are still going on albeit on a much smaller scale
...

So you'll need to do a few different things to get an
XMLHttpRequest object going
...

Working with Microsoft browsers
Microsoft's browser, Internet Explorer, uses the MSXML parser for
handling XML (you can find out more about MSXML in
Resources)
...


However, it's not that easy
...
Look at Listing 3 for the code that
you need to create an XMLHttpRequest on Microsoft browsers
...
Create an XMLHttpRequest object on Microsoft
browsers
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2
...
XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}

All of this won't make exact sense yet, but that's OK
...
For now, you want to get
two core lines into your head:
xmlHttp = new ActiveXObject("Msxml2
...
XMLHTTP");
...
Nice, huh? If neither of these work, the xmlHttp variable
is set to false, to tell your code know that something hasn't worked
...


 AJAX with MySQL database:-

AJAX database example
The following example will demonstrate how a web page can fetch
information from a database with AJAX technology
...


Example explained - The MySQL Database

The database table we use in this example looks like this:
id FirstName

LastName

Age

Hometown

Job

1

Peter

Griffin

41

Quahog

Brewery

2

Lois

Griffin

40

Newport

Piano Teacher

3

Joseph

Swanson

39

Quahog

Police Officer

4

Glenn

Quagmire

41

Quahog

Pilot

Example explained - The HTML page

The HTML page contains a link to an external JavaScript, an HTML form, and
a div element: